Sub topic 3
Adding interaction with StatefulWidget and setState
This chapter assumes you have installed the Flutter SDK, run flutter doctor without blocking errors, and created a project with flutter create. You should know basic Dart syntax, including classes and functions.
Adding state with StatefulWidget
A StatefulWidget is a widget whose appearance can change over time. It pairs with a State object that holds the changing data. Calling setState tells Flutter that the data changed, so Flutter runs build() again and redraws the screen.
Replace lib/main.dart with this counter app:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'First App',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.teal),
),
home: const CounterPage(),
);
}
}
class CounterPage extends StatefulWidget {
const CounterPage({super.key});
@override
State<CounterPage> createState() => _CounterPageState();
}
class _CounterPageState extends State<CounterPage> {
int _count = 0;
void _increment() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Counter')),
body: Center(
child: Text(
'Taps: $_count',
style: Theme.of(context).textTheme.headlineMedium,
),
),
floatingActionButton: FloatingActionButton(
onPressed: _increment,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}Changing _count without setState updates the variable but not the screen. Always wrap state changes in setState.
Iterating with hot reload and hot restart
Run the app with flutter run, then press r in the terminal for hot reload. Hot reload injects changed code into the running app and keeps the current state, so _count survives. Press R for hot restart, which restarts the app and resets all state.
Adding a package
Packages are reusable libraries published on pub.dev. Add the http package with:
flutter pub add http
flutter pub getThe first command writes the dependency into pubspec.yaml. The second downloads it.
Writing your first widget test
Widget tests build a widget in memory and check its behavior without a device. Save this as test/widget_test.dart:
import 'package:flutter_test/flutter_test.dart';
import 'package:my_first_app/main.dart';
void main() {
testWidgets('counter increments when the button is tapped',
(WidgetTester tester) async {
await tester.pumpWidget(const MyApp());
expect(find.text('Taps: 0'), findsOneWidget);
await tester.tap(find.byType(FloatingActionButton));
await tester.pump();
expect(find.text('Taps: 1'), findsOneWidget);
});
}Run it with flutter test.
Debug, profile, and release modes
| Mode | Command | Purpose |
|---|---|---|
| Debug | `flutter run` | Enables hot reload and debugging. Slowest. |
| Profile | `flutter run --profile` | Near-release speed with performance tools. |
| Release | `flutter run --release` | Fully optimized for end users. No debugging. |
Fixing common setup problems
- Missing toolchain pieces: Run
flutter doctor -vand follow each suggested fix. - No devices listed: Run
flutter devices. Start an emulator or simulator, or enable browser or desktop targets. - Package not found after editing
pubspec.yaml: Runflutter pub get. - Hot reload shows stale output: Use hot restart with
R.
Exercise
In the counter app, what happens if you change _count++ to _count++; inside build() without calling setState, and why?
Show answer
Nothing visible happens on screen. The value changes, but build() is not scheduled to run again. Changing a value inside build() also breaks the rule that build should only describe the UI. The fix is to change state only inside setState, from an event handler such as _increment.