Flutter
Increment button
Write an increment callback on FloatingActionButton.
Increment button
To increment the counter, a FloatingActionButton is given to the floatingActionButton parameter of Scaffold. In the button's onPressed callback, the _count variable is incremented by 1 with setState and the screen is rebuilt.
Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_count = _count + 1;
});
},
child: Icon(Icons.add),
),
)
Add indicator with Icon
An Icon is usually given to the child parameter of FloatingActionButton. For incrementing, Icon(Icons.add) is used. This visually tells the user that the button performs an increment action.
Exercise Prepare the increment button
Write a function artirMesaj that prints Artir butonu hazir. Write a StatefulWidget named SayacEkrani; define an int counter variable in its State (starting at 0). In the build method, add a FloatingActionButton to the Scaffold; let onPressed increment the counter by 1 with setState, and child be the plus icon. In main call artirMesaj and start SayacEkrani with runApp.
Show example solution
import 'package:flutter/material.dart';
void artirMesaj() {
print('Artir butonu hazir');
}
class SayacEkrani extends StatefulWidget {
const SayacEkrani({super.key});
@override
State<SayacEkrani> createState() => _SayacEkraniState();
}
class _SayacEkraniState extends State<SayacEkrani> {
int _sayac = 0;
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(child: Text('$_sayac')),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
_sayac = _sayac + 1;
});
},
child: Icon(Icons.add),
),
),
);
}
}
void main() {
artirMesaj();
runApp(const SayacEkrani());
}
Test yourself
-
What is done in the FloatingActionButton's onPressed?
- The app is closed
- The AppBar is hidden
- A new screen is opened
- Counter is incremented by 1 inside setState
Show answer
Counter is incremented by 1 inside setState — In the increment button's onPressed, the counter should be incremented by 1 inside setState; opening a screen, closing the app or hiding the AppBar are not for this purpose.
-
Increment inside setState
FloatingActionButton(
onPressed: () {
____(() {
_sayac = _sayac + 1;
});
},
child: Icon(Icons.add),
)
Show answer
FloatingActionButton(
onPressed: () {
setState(() {
_sayac = _sayac + 1;
});
},
child: Icon(Icons.add),
)
-
Increment button parts
- FloatingActionButton
- Floating increment button
- onPressed
- Callback called on press
- setState
- Rebuilds the screen
- Icon(Icons.add)
- Plus symbol icon
Next lesson: Decrement button