简体   繁体   中英

How flutter_riverpod listens to a list

I want to use flutter_riverpod to watch a list of data. But when I change the data content in the list, the widget is not refreshed.

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(),
        ));
  }

Code link

How to use flutter_riverpod to watch the data changes in the list, thanks!!!

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. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM