Methods on Your Classes
Part of the State Management section of Coddy's Flutter journey. Lesson 5 of 27.
So far your classes held data: a name, a price. A class can also hold the code that changes that data. A function inside a class is called a method:
class Wallet {
int coins = 10;
void earn(int amount) {
coins = coins + amount;
}
}Call a method with a dot, like a field: wallet.earn(3). Inside the method, coins is the field of the wallet it was called on.
Why bother, when the page could write wallet.coins = wallet.coins + 3 itself? Because the rules then live in one place. If a wallet must never go below zero, the spend method checks it, and every button that spends goes through that check.
The widget still calls setState around the call, so the screen shows the new number.
Challenge
EasyRight now Spend 5 takes coins straight from the field, and the wallet goes below zero.
- Add a method
void spend(int amount)toWalletthat takes the coins away only when there are enough. - Make the
Spend 5button callwallet.spend(5)insidesetState.
Try it yourself
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class Wallet {
int coins = 10;
void earn(int amount) {
coins = coins + amount;
}
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
final wallet = Wallet();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: const Text('Wallet')),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Text('${wallet.coins} coins', style: const TextStyle(fontSize: 32)),
const SizedBox(height: 16),
ElevatedButton(
onPressed: () {
setState(() {
wallet.earn(3);
});
},
child: const Text('Earn 3'),
),
ElevatedButton(
onPressed: () {
setState(() {
wallet.coins = wallet.coins - 5;
});
},
child: const Text('Spend 5'),
),
],
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in State Management
2Dart for Models
Methods on Your ClassesGetters in Your ClassesKeep a Field PrivateAdd Up a List With foldPractice on your own: Online Flutter compiler