flutter - 如何从 StreamBuilder 将数据正确保存到我的模型中

标签 flutter dart model stream

所以我想知道将数据保存到模型中的最佳方法是什么。我注意到关于 StreamBuilder 和模型的信息并不多。 (我的意思是两者都在一起)。

这是我当前的模型。

class User {
  String _username, _name, _dateBorn, _gender;

  bool _isObserver, _notifyFriends, _recordAudio, _sendTweet;

  List<dynamic> _friendList;
  List<dynamic> _pendingFriends;

  User(
      this._username,
      this._name,
      this._dateBorn,
      this._gender,
      this._isObserver,
      this._notifyFriends,
      this._recordAudio,
      this._sendTweet,
      this._friendList,
      this._pendingFriends);

  String get username => _username;
  String get name => _name;
  String get dateBorn => _dateBorn;
  String get gender => _gender;

  bool get isObserver => _isObserver;
  bool get notifyFriends => _notifyFriends;
  bool get recordAudio => _recordAudio;
  bool get sendTweet => _sendTweet;

  set setNotifyFriends(bool value) => _notifyFriends = value;
  set setRecordAudio(bool value) => _recordAudio = value;
  set setSendTweet(bool value) => _sendTweet = value;

  List<dynamic> get friendList => _friendList;
  List<dynamic> get pendinFriends => _pendingFriends;
}

这是我当前的 FireStore 数据库。

enter image description here

现在我正在做的就是这个。

StreamBuilder(
            stream:
                FirebaseFirestore.instance.collection('Usuarios').snapshots(),
            builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
              if (!snapshot.hasData) {
                return Center(
                  child: CircularProgressIndicator(),
                );
              }

              var data = snapshot.data!.docs;
              var user;

              data.forEach((element) {
                if (element["username"] == me) {
                  user = User(
                    element["username"],
                    element["realName"],
                    element["date_birth"],
                    element["sexo"],
                    element["isObserver"],
                    element["config"]["notifyFriends"],
                    element["config"]["recordAudio"],
                    element["config"]["sendTweet"],
                    element["friends"],
                    element["pendingFriends"],
                  );
                }
              });

              return FriendsWidget(user);
            }),

但我很确定这不是一个好的实践,将数据提供给模型的最佳实践是什么?不会失去实时更新数据的功能?

谢谢!

最佳答案

We can make use of json_serializable package available in Flutter to ease the JSON parsing and assign it to respective model class instead of assigning it manually.

您可以创建一个方法fromJsontoJson解析 JSONObject。但是,我们可能需要设置一些开发依赖项才能在我们的项目中发挥作用。请参阅Flutter处的文档

使用起来很简单,如下所示

FirebaseFirestore.instance.collection('allUsers').snapshots().listen((event) {
    for (var element in event.docChanges) {
        final modelData = UserModel.fromJson(element.doc.data());
        // Do anything with your user. For example adding to list. 
    }
});

模型类

part 'user_model.g.dart';

@JsonSerializable()
class UserModel {
  @JsonKey(name: 'user_id')
  String userId;

  @JsonKey(name: 'name')
  String name;
  
  UserModel();

  factory UserModel.fromJson(Map<String, dynamic> json) => _$UserModelFromJson(json);

  Map<String, dynamic> toJson() => _$UserModelToJson(this);
}

json_serializable的使用与 firestore在下面的文章中进行了解释。可以作为引用。

firestore-with-flutter-json-annotation

flutter-using-json_serializable-to-serialise

https://livebook.manning.com/book/flutter-in-action/chapter-10/v-7/54

示例链接中提供了详细信息。您可能需要计算出最适合您的要求的方法。

关于flutter - 如何从 StreamBuilder 将数据正确保存到我的模型中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68542604/

相关文章:

dart - 任何 Dart 专家都说明下面的代码是什么 Dart 构造函数?

asp.net-mvc-3 - 在 Controller 中从 MVC3 部分 View 访问模型数据,而不在 View 中显式传递它

python - 检查对象是否存在

android - 释放 TextFormField 关注硬件后退按钮按下

class - 将变量从一个类移到另一个类-Dart Flutter

flutter - 为什么AppBar的automaticImplyLeading没有效果?

android - Firebase crashlytics 仍然悬而未决

java - Java 内存模型中的实例变量

flutter - 在TextEditingController的初始值设定项中只能访问静态成员

android - Flutter可重用表单小部件