I'm building a Flutter app where I use a Dismissible widget to allow users to remove items from a list. I've noticed that the UI updates correctly when an item is dismissed, even if I don't call setState.
here is the code:
@override
_GroceryListScreenState createState() => _GroceryListScreenState();
}
class _GroceryListScreenState extends State<GroceryListScreen> {
List<String> groceryItems = ['Apples', 'Bananas', 'Oranges', 'Milk'];
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Grocery List'),
),
body: ListView.builder(
itemCount: groceryItems.length,
itemBuilder: (context, index) {
return Dismissible(
key: ValueKey(groceryItems[index]),
onDismissed: (direction) {
groceryItems.removeAt(index); // UI updates even without setState
},
background: Container(color: Colors.red),
child: ListTile(
title: Text(groceryItems[index]),
),
);
},
),
);
}
}
It is necessary, groceryItems
just removed an item after onDismissed
, but ListView
haven't noticed that, so you need to call setState
to notify ListView
, failing to do so will cause a RangeError
when you scroll to the end.