text stringlengths 1 372 |
|---|
widget build(BuildContext context) { |
return MaterialApp( |
title: 'flutter demo', |
home: scaffold( |
appBar: AppBar( |
title: const Text('Flutter demo'), |
), |
body: const center( |
child: TapboxA(), |
), |
), |
); |
} |
} |
<code_end> |
<topic_end> |
<topic_start> |
the parent widget manages the widget’s state |
often it makes the most sense for the parent widget |
to manage the state and tell its child widget when to update. |
for example, IconButton allows you to treat |
an icon as a tappable button. IconButton is a |
stateless widget because we decided that the parent |
widget needs to know whether the button has been tapped, |
so it can take appropriate action. |
in the following example, TapboxB exports its state |
to its parent through a callback. because TapboxB |
doesn’t manage any state, it subclasses StatelessWidget. |
the ParentWidgetState class: |
the TapboxB class: |
<code_start> |
import 'package:flutter/material.dart'; |
// ParentWidget manages the state for TapboxB. |
//------------------------ ParentWidget -------------------------------- |
class ParentWidget extends StatefulWidget { |
const ParentWidget({super.key}); |
@override |
State<ParentWidget> createState() => _ParentWidgetState(); |
} |
class _ParentWidgetState extends State<ParentWidget> { |
bool _active = false; |
void _handleTapboxChanged(bool newValue) { |
setState(() { |
_active = newValue; |
}); |
} |
@override |
widget build(BuildContext context) { |
return SizedBox( |
child: TapboxB( |
active: _active, |
onChanged: _handleTapboxChanged, |
), |
); |
} |
} |
//------------------------- TapboxB ---------------------------------- |
class TapboxB extends StatelessWidget { |
const TapboxB({ |
super.key, |
this.active = false, |
required this.onChanged, |
}); |
final bool active; |
final ValueChanged<bool> onChanged; |
void _handleTap() { |
onChanged(!active); |
} |
@override |
widget build(BuildContext context) { |
return GestureDetector( |
onTap: _handleTap, |
child: container( |
width: 200, |
height: 200, |
decoration: BoxDecoration( |
color: active ? Colors.lightGreen[700] : colors.grey[600], |
), |
child: center( |
child: text( |
active ? 'active' : 'inactive', |
style: const TextStyle(fontSize: 32, color: colors.white), |
), |
), |
), |
); |
} |
} |
<code_end> |
<topic_end> |
<topic_start> |
a mix-and-match approach |
for some widgets, a mix-and-match approach makes |
the most sense. in this scenario, the stateful widget |
manages some of the state, and the parent widget |
manages other aspects of the state. |
in the TapboxC example, on tap down, |
a dark green border appears around the box. on tap up, |
the border disappears and the box’s color changes. TapboxC |
exports its _active state to its parent but manages its |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.