【发布时间】:2021-03-20 10:54:17
【问题描述】:
我在提供程序模型中有一个列表项,我想在添加或删除项时为其设置一个观察者侦听器,同时在无状态小部件中更新相关 UI 的一部分(而不是在有状态小部件中使用 setState)。
// Provider
class AppState extends ChangeNotifier {
List<Item> _items;
List<Item> get items => _items;
Future<void> addItem(...) async {
...
notifyListeners();
}
Future<void> deleteItem(...) async {
...
notifyListeners();
}
}
// UI
class _itemList extends StatelessWidget {
@override
Widget build(BuildContext context) {
var appState = context.watch<AppState>(); // If I watch the list, it will rebuild all of it.
return ListView.builder(
itemCount: appState.items.length,
itemBuilder: (context, index) {
final item = appState.items[index];
return ListTile( // How to observer the item of list instead to rebuild all of it?
title: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text(item.name),
Icon(Icons.keyboard_arrow_right, color: Colors.grey)
],
)
});
}
}
【问题讨论】:
-
最好的方法是在 dart 中使用流。尝试学习集团模式。 Provider 有不同的用途,它不用于重建特定的小部件。尝试学习流如何在flutter和flutter_bloc或rxdart中工作