Flutter describes interfaces using widgets. A widget describes part of the display, such as text, spacing or a button. Widgets are nested. A StatelessWidget does not need its own mutable state. A StatefulWidget owns a counter here whose changes update the display.
01Start a Flutter project
Run flutter create --empty first_ui and use cd first_ui to enter the folder. Replace lib/main.dart with the example. flutter run -d chrome starts the web preview. runApp connects the widget tree to Flutter.
import 'package:flutter/material.dart';
void main() => runApp(const MaterialApp(home: CounterScreen()));
class CounterScreen extends StatefulWidget {
const CounterScreen({super.key});
@override
State<CounterScreen> createState() => _CounterScreenState();
}
class _CounterScreenState extends State<CounterScreen> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Vehicle notes')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Entries: $count'),
const SizedBox(height: 16),
FilledButton(
onPressed: () => setState(() => count++),
child: const Text('Add entry'),
),
],
),
),
);
}
}
Run / check
flutter run -d chrome02Read the widget tree
MaterialApp supplies basic behaviour and styling. Scaffold describes the screen structure. Center centres content. Column stacks children vertically. SizedBox adds spacing. Text displays the current value. This structure is nested Dart code rather than a separate markup language.
03Update state
The button calls setState. count increases inside the call. Flutter runs build again and receives a new description of the interface. Database access does not belong in build because this method runs repeatedly.
A button changes Entries: 0 to Entries: 1.
Your exercise
Add a second button that resets the counter to 0.
Show the solution and explanation
Add another FilledButton widget inside children. Use onPressed: () => setState(() => count = 0). Both buttons change the same state. Restarting also resets this simple, not-yet-persisted state.
Project context and sources
The example is simplified for learning. The linked source version shows its use in the project and the checks applied there.