[英]How flutter_riverpod listens to a list
I want to use flutter_riverpod to watch a list of data.我想使用 flutter_riverpod 来观看数据列表。 But when I change the data content in the list, the widget is not refreshed.
但是当我更改列表中的数据内容时,小部件不会刷新。
flutter_riverpod: ^1.0.0-dev.7 flutter_riverpod: ^1.0.0-dev.7
Part of the code is as follows:部分代码如下:
final personProvider = ChangeNotifierProvider((ref) => PersonProvider());
class PersonProvider extends ChangeNotifier {
List<Person> personList;
PersonProvider() {
personList = [
Person(name: "jack", age: 20),
Person(name: "rose", age: 18),
];
}
void changeData() {
// change person
//personList[0].name = "new jack";
// add person
personList.add(Person(name: "lili", age: 25));
notifyListeners();
}
}
The build method of the page is as follows:页面的构建方法如下:
@override
Widget build(BuildContext context) {
// watch List
List<Person> list = ref.watch(personProvider.select((value) => value.personList));
return Scaffold(
floatingActionButton: FloatingActionButton(
child: Icon(Icons.change_circle),
onPressed: () {
// modify the data of list
ref.read(personProvider).changeData();
},
),
appBar: AppBar(),
body: Column(
children: list
.map((person) => ListTile(
title: Text(person.name),
subtitle: Text("${person.age}"),
))
.toList(),
));
}
How to use flutter_riverpod to watch the data changes in the list, thanks!!!如何使用flutter_riverpod查看列表中的数据变化,谢谢!!!
Taking some liberty to change your code around just a bit;稍微改变一下你的代码; when working with Riverpod, I'll use
StateNotifier
over ChangeNotifier
any day of the week.在使用 Riverpod 时,我将在一周中的任何一天使用
StateNotifier
不是ChangeNotifier
。 It allows, in my opinion, for more structured logic.在我看来,它允许更结构化的逻辑。 Your code would look like this.
你的代码看起来像这样。
class PersonNotifier extends StateNotifier<List<Person>> {
PersonNotifier()
: super([
Person(name: "jack", age: 20),
Person(name: "rose", age: 18),
]);
void changeData(Person person) {
state = [...state, person];
}
}
final StateNotifierProvider<PersonNotifier, List<Person>> personProvider =
StateNotifierProvider((ref) => PersonNotifier());
And you can then listen for your state in your code like this.然后你可以像这样在你的代码中监听你的状态。
List<Person> list = ref.watch(personProvider);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.