I'm trying to build a page in which users can add and remove elements from a list. I'm struggling with a problem. When I remove an element, the model is updated correctly while the UI is updated but in a wrong way: only the last element of the list is removed.
I'm using Flutter 1.5.4.
I already using simpler elements for the list and I tried to build a new project with only this page to remove all possible problems, but it still doesn't work correctly.
I also tried using a Column instead of a List but the result is always the same.
main.dart:
import 'package:flutter/material.dart';
import './widget.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: Text('Hello'),
),
body: Center(
child: SectionWidget(),
),
),
);
}
}
widget.dart:
import 'package:flutter/material.dart';
class SectionWidget extends StatefulWidget {
_SectionWidgetState createState() => new _SectionWidgetState();
}
class _SectionWidgetState extends State<SectionWidget> {
List<String> _items = List<String>();
@override
Widget build(BuildContext context) {
List<Widget> children = [
ListTile(
title: Text(
"Strings",
style: TextStyle(fontWeight: FontWeight.bold),
),
trailing: IconButton(
icon: Icon(Icons.add_circle),
onPressed: () => setState(() {
_items.add('item ${_items.length}');
print("Adding "+ _items.last);
}),
),
),
];
children.addAll(_buildForms());
return ListView(
children: children,
);
}
List<Widget> _buildForms() {
List<Widget> forms = new List<Widget>();
print("Strings:" + _items.toString());
for (String item in _items) {
forms.add(
ListTile(
leading: Icon(Icons.person),
title: TextFormField(
initialValue: item,
),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: () => setState(() {
print("Removing $item");
_items.remove(item);
}),
),
),
);
}
return forms;
}
}
If I add 4 items to the list and then remove "item 1", this is the output on the console:
I/flutter ( 4192): Strings:[]
I/flutter ( 4192): Adding item 0
I/flutter ( 4192): Strings:[item 0]
I/flutter ( 4192): Adding item 1
I/flutter ( 4192): Strings:[item 0, item 1]
I/flutter ( 4192): Adding item 2
I/flutter ( 4192): Strings:[item 0, item 1, item 2]
I/flutter ( 4192): Adding item 3
I/flutter ( 4192): Strings:[item 0, item 1, item 2, item 3]
I/flutter ( 4192): Removing item 1
I/flutter ( 4192): Strings:[item 0, item 2, item 3]
Which is correct, as "item 1" was removed from the list, but if I look at the UI, this is what i get:
The number of elements in the list is correct, the model is correct, but the elements shown are wrong.
How do I fix this? Am I doing something wrong or is it a bug of Flutter?
What you can do is pass to the ListView
the Key
which will contain the length of the elements in the list.
ListView(
key: Key(myList.length.toString()),
children: myList.map(...),
),
Why it works?
It causes the whole ListView
to rebuild itself from scratch but only when the length on your list changes. What's important is that it doesn't happen in other cases (like typing inside a TextField) because such action would cause you to lose focus on every letter type.
Hope it helps ;)
This is not a solution but an explanation, refer to Marcin Szałek's comment for the solution.
The reason that the ListView
does not rerender as expected is that the TextFormField
is a stateful widget. When you rebuild the widgets, you need to take note that there are 3 trees under the hood, which are the Widget, Element and RenderObject tree. The RenderObject is the visual representation, and is directly based on the Element. Whereas the Element is directly based on the Widget, and the Widget is just the configuration, i.e. what you type in code.
When first instantiating a widget, a corresponding element is created. However, when you call setState()
to change the _items list, the widget is rebuild, but the element is not destroyed and recreated. Rather, in order to maximise efficiency, Flutter is made such that it first compares any differences between the initial ListTile
widgets and the rebuild ListTile
widgets. In this case, initially there are 4 tiles, and afterwards there are 3 tiles. Instead of recreating new tiles, the elements of the second and third tiles are updated to have the attributes of the rebuild ListTile
widgets (and no changes occur for the first tile because the widget/configuration before and after is the same). The 4th element is popped from the Element tree. This video by the official Flutter team does a great job at explaining the three trees.
Using Dart's Devtools, you can find no change in the key/id of the third element. When you inspect the third ListTile
, before and after the key is #3dded.
Initial
After deletion
To remove the elements from the tree and then put them back in, attach a key to the ListView
as commented by Marcin Szałek. For stateful widgets, elements will be updated when the corresponding new widget is of the same widget type and has the same key. Without explicitly specifying the key, the element will only check whether it is of the same type as the corresponding widget, and as all the widgets are of runtime type ListTile
, then there would not be any update of the elements, thus you see item 0 and item 1 instead of item 0 and item 2. I recommend that you read more about keys here.
Using Dart's Devtools, you can find the change in the key of the third ListTile
. Initially, when it was item 1, the key was #5addd. Then, when item 1 is deleted, the key changes to #26044.
Initial
After deletion
The reason for removing not updating the deleted element is the second widget is stateful widget it needs force rendering in some case
use this code to get reload the view by overriding the didUpdateWidget method
@override
void didUpdateWidget(LoadImageFromPathAsync oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget != widget) {
setState(() {});
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With