final Variables
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 16 of 34.
final is the other word for a value that does not change. A final variable gets its value once and can never be given another:
final int total = _tickets * 12;
total = 50; // error: total is finalThe difference from const is when the value is known. A const value is known when you write the code, like 12. A final value can be worked out while the app runs, like _tickets * 12, which depends on how many tickets there are right now.
const int price = 12; // always 12
final int total = _tickets * price; // known when build runsA final variable at the top of build is worked out again on every build, so after setState it holds the new total. Use final for a value you set once and only read, and a plain int or String for one you change, like _tickets.
Challenge
EasyA ticket costs 12. At the top of build, add const int price = 12; and a final variable total that is _tickets times price. Show it as Total: 12 in place of Total: ?, so it reads Total: 24 after one more ticket.
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 _tickets = 1;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Tickets')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('Tickets: $_tickets', style: const TextStyle(fontSize: 24)),
Text('Total: ?', style: const TextStyle(fontSize: 24)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
setState(() {
_tickets++;
});
},
child: const Text('Add a ticket'),
),
],
),
),
);
}
}
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