【问题标题】:I tried to display 'DateTime' on flutter UI get from firestore but show " Bad state: field does not exist within the DocumentSnapshotPlatform "我试图在从 firestore 获取的 flutter UI 上显示 \'DateTime\' 但显示 \" Bad state: field does not exist within the DocumentSnapshotPlatform \"
【发布时间】:2023-01-29 21:07:55
【问题描述】:

我必须对我之前的问题做一些更改,因为现在用户生日(年、月和日)未显示在 UI 上,并且还在控制台上显示此错误“ E/flutter ( 7311): [ERROR:flutter/runtime /dart_vm_initializer.cc(41)] 未处理的异常:错误状态:DocumentSnapshotPlatform 中不存在字段”

错误

但是当评论生日时,其他数据显示得很好。

我不明白获取生日的错误是什么。

数据库生日参数截图

我只想显示年月日

在显示这个的 UI 上

代码

模型类

class Users {
  String? id;
  String? name;
  String? url;
  DateTime? birthday;

  Users({
    this.id,
    this.name,
    this.url,
    this.birthday,
  });

  Users.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    url = json['url'];
    birthday = json["birthday"]?.toDate();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['url'] = this.url;
    data['birthday'] = this.birthday;
    return data;
  }
}

控制器类



User? user = FirebaseAuth.instance.currentUser;
UserModel loggedInUser = UserModel();
@override
Future<List<Users>> fetchRecords() async {
  var records = await FirebaseFirestore.instance.collection('Users').get();
  return mapRecords(records);
}

List<Users> mapRecords(QuerySnapshot<Map<String, dynamic>> records) {
  var list = records.docs
      .map(
        (user) => Users(
          id: user.id,
          name: user['name'],
          url: user['url'],
           birthday: user['birthday'].toDate(),
        ),
      )
      .toList();

  return list;
}

用户界面代码

SizedBox(
  child: SizedBox(
      width: width * 0.94,
      height: height * 0.95,
      child: FutureBuilder<List<Users>>(
          future: fetchRecords(),
          builder: (context, snapshot) {
            if (snapshot.hasError) {
              return Text('Error: ${snapshot.error}');
            } else {
              List<Users> data = snapshot.data ?? [];

              return ListView.builder(
                  itemCount: data.length,
                  itemBuilder: (context, index) {
                    return (SizedBox(
                      height: 100,
                      child: Card(
                        color:
                            Colors.white.withOpacity(0.8),
                        shape: RoundedRectangleBorder(
                          side: const BorderSide(
                            color: Colors.greenAccent,
                          ),
                          borderRadius:
                              BorderRadius.circular(20.0),
                        ),
                        child: Column(
                          children: <Widget>[
                            ListTile(
                                leading: Image.network(
                                  '${data[index].url}',
                                  height: 30,
                                  fit: BoxFit.cover,
                                ),
                                title: Text(
                                    '${data[index].name}' ??
                                        ' '),
                                        subtitle: Text(
                                    '${data[index].birthday?.year}/${data[index].birthday?.month}/${data[index].birthday?.day}'),
                                trailing: ElevatedButton(
                                  child: Text('View'),
                                  onPressed: () {
                                    
                                  },
                                ))
                          ],
                        ),
                      ),
                    ));
                  });
            }
          }))),

如何解决此错误并获取用户生日?

【问题讨论】:

  • pet这一行birthday: pet['birthday'].toDate()来自哪里?
  • 哦..对不起我的错,我改变了它但仍然是同样的错误
  • @nibbo 你知道我的代码有什么错误吗
  • 您好根据您的错误更新了代码。

标签: flutter firebase datetime google-cloud-firestore


【解决方案1】:

我已经根据您提供的代码重新创建了设置,您的 UI 代码是正确的,但是您的 fetchRecords() 可以使用一些 Typing CollectionReference and DocumentReference 所以请尝试下面的代码,因为它向我显示了 UI 中的正确生日

模型类:

class Users {
  final String id; final String name; final String url; final DateTime birthday;

  Users({
    required this.id, required this.name, required this.url, required this.birthday,
  });

  Users.fromJson(Map<String, dynamic> json)
      : this(
            id: json['id']! as String, 
            name: json['name']! as String, 
            url: json['url']! as String,
            birthday: DateTime.fromMillisecondsSinceEpoch(json['birthday'].toInt()));

  Map<String, Object?> toJson() {
    return {'id': id, 'name': name, 'url': url, 'birthday': birthday.millisecondsSinceEpoch};
  }
}

fetchRecords()mapRecords() 将是:

User user = FirebaseAuth.instance.currentUser!;
UserModel loggedInUser = UserModel();

Future<List<Users>> fetchRecords() async {
    final usersRef =
        FirebaseFirestore.instance.collection('users').withConverter<Users>(
              fromFirestore: (snapshot, _) => Users.fromJson(snapshot.data()!),
              toFirestore: (user, _) => user.toJson(),
            );

    QuerySnapshot<Users> users = await usersRef.get();
    return mapRecords(users);
  }

List<Users> mapRecords(QuerySnapshot<Users> records) {
    var list = records.docs
        .map(
          (user) => Users(
            id: user.id, 
            name: user['name'], 
            url: user['url'], 
            birthday: user['birthday'].toDate(),
          ),
        ).toList();
    return list;
  }

在我看来,出于某种原因,最好使用 FlutterFire 提供的类型化类技术,而不是使用任何自定义类型化技术。

【讨论】:

  • 感谢您的支持 !!!我试过你的代码现在显示“E/flutter ( 8616): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: type 'DateTime' is not a subtype of type 'String'”这个错误。
  • 您能否确认您的 firebase 控制台中的生日类型是什么?
猜你喜欢
  • 1970-01-01
  • 2021-12-20
  • 1970-01-01
  • 2021-10-01
  • 2021-01-21
  • 2015-10-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多