I'm struggling with this for few days, but can't figure it out. I have a simple widget, where I want to dynamically add and remove inputs (for sets/reps). The problem is, if I'm removing let's say the first item, the last item gets removed from UI.
I've created a dartpad for the app: dartpad
My main.dart:
import 'package:flutter/material.dart';
final Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark().copyWith(scaffoldBackgroundColor: darkBlue),
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SetBuilderWidget();
}
}
class TempSet {
int weight;
int rep;
int order;
TempSet(this.order, this.weight, this.rep);
}
class SetBuilderWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() => _SetBuilderWidgetState();
}
class _SetBuilderWidgetState extends State<SetBuilderWidget> {
final sets = [];
final List<TempSet> tempSet = [];
Widget _row(int index) {
return Row(
children: <Widget>[
Text("Set $index"),
Flexible(
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 40),
child: TextField(
decoration: InputDecoration(
labelText: "Rep count",
),
),
),
),
IconButton(
icon: Icon(Icons.delete),
onPressed: () => _removeSet(index),
),
],
);
}
List<Widget> _rows() {
return tempSet.map((s) => _row(s.order)).toList();
}
void _addSet() {
if (tempSet.length == 0) {
tempSet.add(TempSet(0, null, null));
} else {
final lastSet = tempSet.last;
tempSet.add(TempSet(tempSet.indexOf(lastSet) + 1, null, null));
}
}
void _removeSet(int index) {
setState(() {
tempSet.removeAt(index);
_updateIndexes();
});
}
void _updateIndexes() {
tempSet.asMap().forEach((index, s) {
s.order = index;
});
}
@override
void initState() {
_addSet();
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
..._rows(),
RaisedButton(
onPressed: () {
setState(() {
_addSet();
});
},
child: Text("Add set"),
)
],
);
}
}
Issue: