在 flutter (dart) 中使用模型类

Dan*_* R. 2 dart flutter

我正在尝试创建一个模型类,其中包含一些方法来简化从 Firebase 检索信息的过程。

我有一个“未注册”页面,用户单击“使用谷歌登录”按钮。如果我的用户已经注册,它会检查数据库以查看他是否完成了他的个人资料,否则它会使用一个字段将基本数据写入数据库,profileCompleted: false并将用户重定向到个人资料页面,以便他可以完成他的个人资料。

我试图在这里使用一个模型,但我遇到了各种各样的错误(刚刚开始学习 flutter/dart)。

我将分享一些代码,如果还不够,请告诉我!

未注册页面。

    if (user != null) {
      await prefs.setString('id', user.uid);
      // Check is already sign up
      final QuerySnapshot result = await Firestore.instance
          .collection('users')
          .where('id', isEqualTo: user.uid)
          .getDocuments();
      final List<DocumentSnapshot> documents = result.documents;

      if (documents.length == 0) {
        debugPrint("User not in DB ?");
        //debugPrint(userInfo.toString());
        // Update data to server if new user

        Firestore.instance.collection('users').document(user.uid).setData({
          'id': user.uid,
          'nickname': user.displayName,
          'photoUrl': user.photoUrl,
          'email': user.email,
          'createdAt': DateTime.now(),
          'provider': user.providerId,
          'profileCompleted': false,
          'bloodType': 'A',
          'rhType': 'Negativ',
          'donatedBefore': 'Nu',
          'lastDonation': '0'
        });
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => CompleteProfile(
                      currentUserId: user.uid,
                      userInfo: documents.single,
                    )));
      } else if (documents.single["profileCompleted"] == false) {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => CompleteProfile(
                      currentUserId: user.uid,
                      userInfo: documents.single,
                    )));
      } else {
        Navigator.push(
            context,
            MaterialPageRoute(
                builder: (context) => HomePage(
                      currentUserId: user.uid,
                      userInfo: documents.single,
                    )));
      }
    }
Run Code Online (Sandbox Code Playgroud)

完整的个人资料页面

class CompleteProfile extends StatefulWidget {
  final String currentUserId;
  final userInfo;
  static const routeName = '/profile';
  final User user;

  CompleteProfile(
      {Key key,
      this.title,
      @required this.currentUserId,
      @required this.userInfo,
      this.user})
      : super(key: key);

  final String title;

  @override
  _CompleteProfileState createState() => _CompleteProfileState(user,
      currentUserId: this.currentUserId, userInfo: this.userInfo);
}

class _CompleteProfileState extends State<CompleteProfile> {
  User user;

  _CompleteProfileState(this.user,
      {Key key, @required this.currentUserId, @required this.userInfo});
  final String currentUserId;
  final userInfo;
Run Code Online (Sandbox Code Playgroud)

我的问题是,如果我尝试设置这样的下拉菜单 ->

child: ListTile(
title: DropdownButton<String>(
items: _bloodTypes.map((String value) {
return DropdownMenuItem<String>(
value: value, child: Text(value));
}).toList(),
style: textStyle,
value: retrieveBloodType(user.bloodType),
onChanged: (value) => updateBloodType(value),
Run Code Online (Sandbox Code Playgroud)

并在默认值->

  String retrieveBloodType(String value) {
    return _bloodType;
  }
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,提示我为 null。

我的想法是User用类似的东西初始化模型User user = new User(userInfo["id"],userInfo["email"]....,其中userInfo是从 firebase 检索的对象。但是,这会引发另一个错误,即只能在初始化程序中访问静态成员。

我的模型非常简单,所以这里是一个预览(几行,不是整个模型)。

class User {
  int _id;
  String _nickname;
  int get id => _id;
  String get nickname => _nickname;
  set bloodType(String newBloodType) {
    if (newBloodType.length <= 50 && newBloodType != null) {
      _bloodType = newBloodType;
    }
  }
Run Code Online (Sandbox Code Playgroud)

知道 id 必须如何改变它才能工作吗?我考虑使用模型的唯一原因是简化屏幕小部件(这样我就可以将所有 firebase 逻辑添加到模型而不是小部件中)。

Tai*_*yev 7

我就是这样做的

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  final String userName;
  final String email;
  final String name;
  final String phoneNumber;
  final String profilePictureUrl;
  final Timestamp creationDate;

  const User(
    this.userName,
    this.email,
    this.name,
    this.phoneNumber,
    this.profilePictureUrl,
    this.creationDate
  );

  factory User.fromDocument(DocumentSnapshot document) {
    return User(
      document['userName'],
      document['email'],
      document['name'],
      document['phoneNumber'],
      document['profilePictureUrl'],
      document['creationDate']
    );
  }
Run Code Online (Sandbox Code Playgroud)