Flutter
Decrement button
Write a decrement callback on a second FAB.
Decrement button
To decrement the counter, a second FloatingActionButton is used. In this button's onPressed callback, the _count variable is decremented by 1 with setState. The two buttons are usually placed in a Row with a common parent for FloatingActionButton.
FloatingActionButton(
onPressed: () {
setState(() {
_count = _count - 1;
});
},
child: Icon(Icons.remove),
)
Two buttons with Row
To show two FloatingActionButtons in Scaffold's floatingActionButton parameter, they are wrapped in a Row. Row lays the buttons out side by side horizontally; each button carries its own onPressed callback.
Row(
children: [
FloatingActionButton(onPressed: () {}, child: Icon(Icons.remove)),
FloatingActionButton(onPressed: () {}, child: Icon(Icons.add)),
],
)
Exercise Write increment and decrement functions
Write a StatefulWidget named SayacEkrani; define an int counter variable in its State (starting at 0). The artir function increments the counter by 1 with setState, and the azalt function decrements the counter by 1 with setState. In main, create a State instance, call artir then azalt, and print the result.
Show example solution
import 'package:flutter/material.dart';
class SayacEkrani extends StatefulWidget {
const SayacEkrani({super.key});
@override
State<SayacEkrani> createState() => _SayacEkraniState();
}
class _SayacEkraniState extends State<SayacEkrani> {
int _sayac = 0;
void artir() {
setState(() {
_sayac = _sayac + 1;
});
}
void azalt() {
setState(() {
_sayac = _sayac - 1;
});
}
}
void main() {
final state = _SayacEkraniState();
state.artir();
state.azalt();
print(state._sayac);
}
Test yourself
-
Which is used for the Icon parameter of the decrement button?
- Icon(Icons.menu)
- Icon(Icons.add)
- Icon(Icons.remove)
- Icon(Icons.search)
Show answer
Icon(Icons.remove) — To visually show decrement, Icon(Icons.remove) is used; add is for increment, search for search, and menu for menu.
-
Decrement inside setState
FloatingActionButton(
onPressed: () {
____(() {
_sayac = _sayac - 1;
});
},
child: Icon(Icons.remove),
)
Show answer
FloatingActionButton(
onPressed: () {
setState(() {
_sayac = _sayac - 1;
});
},
child: Icon(Icons.remove),
)
-
Decrement button parts
- FloatingActionButton
- Floating decrement button
- onPressed
- Callback called on press
- decrement
- A decrement operation
- Icon(Icons.remove)
- Minus symbol icon
Next lesson: Summary - Counter app