const Widgets
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 15 of 34.
const in front of a value means: this is fixed when you write the code and never changes. const Text('Score') will show Score for as long as the app runs.
Why tell Dart that? When setState builds the screen again, Flutter can skip every const widget, because it knows nothing inside it changed. That is why Flutter's code editors, such as VS Code and Android Studio, underline a widget that could be const and suggest adding it. From here on, the apps in this course use const where it fits.
const reaches inside: on a widget, everything in its parentheses is const too. So you write it once, on the outermost widget that never changes:
const Column(
children: [
Text('Score'),
Icon(Icons.star),
],
)A variable can change, so it can never be inside const. Put Text('$_score') in that column and Dart refuses to compile it, with the error "Not a constant expression". The fix: take const off the column and put it on each child that does not change:
Column(
children: [
const Text('Score'),
Text('$_score'),
],
)Challenge
MediumThe score goes up when you press the plus button, but the screen never shows it. Under Score, add Text('$_score') in size 48. You will need to move const from the Column to the widgets in it that never change.
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: const HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _score = 0;
void _goal() {
setState(() {
_score++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Game')),
body: Center(
child: const Column(
mainAxisSize: MainAxisSize.min,
children: [
Icon(Icons.sports_soccer, size: 64),
Text('Score', style: TextStyle(fontSize: 24)),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _goal,
child: const Icon(Icons.add),
),
);
}
}
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