Write a StatefulWidget
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 12 of 34.
This time you write the StatefulWidget yourself. The screen says I feel Sleepy, and a press of Drink coffee should change it to I feel Awake. As a StatelessWidget it never can.
Turning a StatelessWidget into a StatefulWidget takes three steps:
- Change
extends StatelessWidgettoextends StatefulWidget, and replace itsbuildwithcreateState. - Write the
Stateclass under it and movebuildthere, unchanged. - Move the changing variable out of
buildto the top of theStateclass.
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String _mood = 'Sleepy';
@override
Widget build(BuildContext context) {
...
}
}Step 3 matters. A variable at the top of build is made again every time build runs, so after setState it would be back to 'Sleepy'. At the top of the State class it is made once, and keeps the value you give it.
Challenge
MediumTurn HomePage into a StatefulWidget with a _HomePageState class. Keep the mood in String _mood = 'Sleepy'; at the top of the State, and make Drink coffee change it to 'Awake' with setState.
Try it yourself
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(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatelessWidget {
const HomePage({super.key});
@override
Widget build(BuildContext context) {
String mood = 'Sleepy';
return Scaffold(
appBar: AppBar(title: Text('Mood')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('I feel $mood', style: TextStyle(fontSize: 32)),
SizedBox(height: 16),
ElevatedButton(
onPressed: () {},
child: Text('Drink coffee'),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Making It Interactive
Practice on your own: Online Flutter compiler