【问题标题】:How can I use a stream with a regular provider, updating the local values as the stream is delivered如何将流与常规提供程序一起使用,在传输流时更新本地值
【发布时间】:2021-03-13 13:17:12
【问题描述】:

所以我有这样的东西,它可以与 streamprovider 一起工作。

Stream<List<AppUser>> streamUsers() {
    return firestore.collection('users').snapshots().map(
          (snapshot) => snapshot.docs
              .map((document) => AppUser.fromJson(document.data()))
              .toList(),
        );
  }

我想要实现的是这样的,流将在后台运行,并且每次传输数据时,它都会更新我的提供程序中的本地变量,并通过这种方式通过提供程序通知我的小部件。这是坏主意吗?如果有,为什么?

class AppUsers with ChangeNotifier {
  FirebaseFirestore firestore = FirebaseFirestore.instance;

  List<AppUser> _users;

  List<AppUser> get users => _users;

  void streamUsers() {
    List<AppUser> users = [];
    firestore
        .collection('users')
        .snapshots()
        .map((snapshot) => snapshot.docs.map((document) {
              AppUser user = AppUser.fromJson(document.data());
              users.add(user);
            }));
    _users = users;
    notifyListeners();
  }
}

更新

我能够通过以下代码实现这一点,并在我的应用加载时调用 init()。我想避免在我的应用程序加载时调用 init。有没有更清洁的方法?

  List<AppUser> _users = [];

  List<AppUser> get users => _users;

  init() {
    streamUsers().listen((event) {
      _users = event;
      notifyListeners();
    });
  }

  Stream<List<AppUser>> streamUsers() {
    return firestore.collection('users').snapshots().map(
          (snapshot) => snapshot.docs
              .map((document) => AppUser.fromJson(document.data()))
              .toList(),
        );
  }

【问题讨论】:

    标签: flutter dart flutter-provider


    【解决方案1】:

    删除init函数并通过再次映射使用每个流事件的通知侦听器:

     Stream<List<AppUser>> streamUsers() {
        return firestore.collection('users').snapshots().map(
              (snapshot) => snapshot.docs
                  .map((document) => AppUser.fromJson(document.data()))
                  .toList(),
            ).map((users) {
             _users = users;
             notifyListeners();
        });
      }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-20
      • 2018-02-09
      • 2020-03-17
      • 2019-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多