1// Best Practice: Stable ValueKey in dynamic lists & Safe Async State update
2class TodoListScreen extends StatefulWidget {
3 const TodoListScreen({super.key});
4
5 @override
6 State<TodoListScreen> createState() => _TodoListScreenState();
7}
8
9class _TodoListScreenState extends State<TodoListScreen> {
10 final List<TodoItem> _items = [];
11 bool _isLoading = false;
12
13 Future<void> _fetchData() async {
14 setState(() => _isLoading = true);
15
16 // Simulate network delay
17 await Future.delayed(const Duration(seconds: 2));
18
19 // CRITICAL: Guard against unmounted widget after async gap
20 if (!mounted) return;
21
22 setState(() {
23 _isLoading = false;
24 _items.addAll([
25 TodoItem(id: 'task-101', title: 'Impeller Architecture Review'),
26 TodoItem(id: 'task-102', title: 'DevTools Profile Session'),
27 ]);
28 });
29 }
30
31 @override
32 Widget build(BuildContext context) {
33 if (_isLoading) return const Center(child: CircularProgressIndicator());
34
35 return ListView.builder(
36 itemCount: _items.length,
37 itemBuilder: (context, index) {
38 final item = _items[index];
39 // Stable ValueKey ensures Flutter preserves state if items are reordered/removed
40 return ListTile(
41 key: ValueKey(item.id),
42 title: Text(item.title),
43 );
44 },
45 );
46 }
47}