text
stringlengths
1
372
widget build(BuildContext context) {
// this method is rerun every time setState is called,
// for instance, as done by the _increment method above.
// the flutter framework has been optimized to make
// rerunning build methods fast, so that you can just
// rebuild anything that needs updating rather than
// having to individually changes instances of widgets.
return row(
mainAxisAlignment: MainAxisAlignment.center,
children: <widget>[
ElevatedButton(
onPressed: _increment,
child: const Text('Increment'),
),
const SizedBox(width: 16),
Text('Count: $_counter'),
],
);
}
}
void main() {
runApp(
const MaterialApp(
home: scaffold(
body: center(
child: counter(),
),
),
),
);
}
<code_end>
you might wonder why StatefulWidget and state are separate objects.
in flutter, these two types of objects have different life cycles.
widgets are temporary objects, used to construct a presentation of
the application in its current state. state objects, on the other
hand, are persistent between calls to
build(), allowing them to remember information.
the example above accepts user input and directly uses
the result in its build() method. in more complex applications,
different parts of the widget hierarchy might be
responsible for different concerns; for example, one
widget might present a complex user interface
with the goal of gathering specific information,
such as a date or location, while another widget might
use that information to change the overall presentation.
in flutter, change notifications flow “up” the widget
hierarchy by way of callbacks, while current state flows
“down” to the stateless widgets that do presentation.
the common parent that redirects this flow is the state.
the following slightly more complex example shows how
this works in practice:
<code_start>
import 'package:flutter/material.dart';
class CounterDisplay extends StatelessWidget {
const CounterDisplay({required this.count, super.key});
final int count;
@override
widget build(BuildContext context) {
return Text('Count: $count');
}
}
class CounterIncrementor extends StatelessWidget {
const CounterIncrementor({required this.onPressed, super.key});
final VoidCallback onPressed;
@override
widget build(BuildContext context) {
return ElevatedButton(
onPressed: onPressed,
child: const Text('Increment'),
);
}
}
class counter extends StatefulWidget {
const counter({super.key});
@override
State<Counter> createState() => _CounterState();
}
class _CounterState extends State<Counter> {
int _counter = 0;
void _increment() {
setState(() {
++_counter;
});
}
@override
widget build(BuildContext context) {
return row(
mainAxisAlignment: MainAxisAlignment.center,
children: <widget>[
CounterIncrementor(onPressed: _increment),
const SizedBox(width: 16),
CounterDisplay(count: _counter),
],
);
}
}
void main() {
runApp(
const MaterialApp(