A Counter Up and Down
Part of the Making It Interactive section of Coddy's Flutter journey. Lesson 13 of 34.
A function can live inside the State class too. There it can read the State's variables and call setState:
void _increase() {
setState(() {
_count++;
});
}_count++ is short for _count = _count + 1, and _count-- takes one away. A function that belongs to a class is called a method, and a private one starts with _, like the variables.
Hand it to a button by its name, with no parentheses, as in Your Own Functions: IconButton(icon: Icon(Icons.add), onPressed: _increase).
Challenge
EasyThe counter only goes up. Add a method _decrease that takes one away inside setState, and an IconButton with Icons.remove before the number that calls it.
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 StatefulWidget {
const HomePage({super.key});
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int _count = 0;
void _increase() {
setState(() {
_count++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Counter')),
body: Center(
child: Row(
mainAxisSize: MainAxisSize.min,
children: [
Text('$_count', style: TextStyle(fontSize: 48)),
IconButton(icon: Icon(Icons.add), onPressed: _increase),
],
),
),
);
}
}
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