Complete the code to create a simple stateful widget that updates a counter.
class CounterWidget extends StatefulWidget { @override _CounterWidgetState createState() => _CounterWidgetState(); } class _CounterWidgetState extends State<CounterWidget> { int _count = 0; void _increment() { setState(() [1]); } @override Widget build(BuildContext context) { return Column( children: [ Text('Count: $_count'), ElevatedButton(onPressed: _increment, child: Text('Increment')), ], ); } }
Using setState with _count += 1 updates the counter and refreshes the UI.
Complete the code to lift state up by passing a callback to a child widget.
class ParentWidget extends StatefulWidget { @override _ParentWidgetState createState() => _ParentWidgetState(); } class _ParentWidgetState extends State<ParentWidget> { int _count = 0; void _increment() { setState(() { _count++; }); } @override Widget build(BuildContext context) { return ChildWidget(onPressed: [1]); } } class ChildWidget extends StatelessWidget { final VoidCallback onPressed; ChildWidget({required this.onPressed}); @override Widget build(BuildContext context) { return ElevatedButton(onPressed: onPressed, child: Text('Increment')); } }
The parent passes its _increment method as a callback to the child, so the child can trigger state changes.
Fix the error in this code that tries to update state without calling setState.
class Counter extends StatefulWidget { @override _CounterState createState() => _CounterState(); } class _CounterState extends State<Counter> { int _count = 0; void increment() { [1]; } @override Widget build(BuildContext context) { return Column( children: [ Text('Count: $_count'), ElevatedButton(onPressed: increment, child: Text('Increment')), ], ); } }
State changes must be wrapped in setState to update the UI properly.
Fill both blanks to create a provider that shares state across widgets.
class CounterModel extends ChangeNotifier { int _count = 0; int get count => _count; void increment() { _count++; [1]; } } void main() { runApp( ChangeNotifierProvider( create: (context) => CounterModel(), child: [2], ), ); }
Calling notifyListeners() tells widgets to rebuild. MyApp() is the root widget wrapped by the provider.
Fill all three blanks to consume the provider state and update UI.
class CounterDisplay extends StatelessWidget { @override Widget build(BuildContext context) { final counter = Provider.of<CounterModel>(context, listen: [1]); return Column( children: [ Text('Count: ${counter.[2]'), ElevatedButton( onPressed: counter.[3], child: Text('Increment'), ), ], ); } }
Listening is true to rebuild on changes. Access count to show value and call increment to update.