I made a simple program with a Plus Button and a Minus Button that generates numbers successively. Generating the numbers with the Plus Button works totally fine but, I tried to delete the numbers with the Minus Button but can't figure this out.
`import 'package:flutter/material.dart';
void main() {
runApp(App());
}
class App extends StatefulWidget {
@override
State<App> createState() => _AppState();
}
// the state of the stateful widget is the one that holds the data and the ui of the widget
class _AppState extends State<App> {
List<int> numbers = [];
int counter = 0;
void onClickedPlus() {
setState(() {
numbers.add(numbers.length);
}); //setState function is a function that we use to notify our state class that the data has changed
}
void onClickedMinus() {
setState(() {
numbers.remove(numbers.length);
}); //setState function is a function that we use to notify our state class that the data has changed
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color(
0xFFF4EDDB), //Color.fromRGBO => red, green, blue, opacity
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'Click Count',
style: TextStyle(fontSize: 30),
),
for (var n in numbers) Text('$n'),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
iconSize: 40,
onPressed: onClickedPlus,
icon: const Icon(Icons.add_box_rounded),
),
IconButton(
iconSize: 40,
onPressed: onClickedMinus,
icon: const Icon(Icons.remove_circle_outline_rounded),
),
],
),
],
),
),
),
);
}
}`
I'm expecting to delete the numbers successively with clicking the Minus Button.
CodePudding user response:
List.remove(item)
removes the first occurrence of value from this list.
So numbers.remove(numbers.length);
is not removing the last number because numbers.length
is always greater than the last number in the list by one. Instead, you should use List.removeLast()
.
void onClickedMinus() {
setState(() {
numbers.removeLast();
});
}
CodePudding user response:
The way your code is written the remove case will always fail. Let me explain why,
your list is of length 0 at first and 1st add button will add 0 to the list. Next add button will add 1 to the list. Now, when you click on minus button the length is 2 but the list only contains [0,1]. So this will never work. Instead,
you can write
void onClickedMinus() {
setState(() {
numbers.remove(numbers.length-1);
}); //setState function is a function that we use to notify our state class that the data has changed
}
this will delete the last element from the list.