【问题标题】:I am getting error while uploading date data to firestore in flutter将日期数据上传到 flutter 时出现错误
【发布时间】:2022-12-06 08:38:44
【问题描述】:
class User {
  String id;
  final DateTime birthday;

User(
      {this.id, required this.birthday,});

  Map<String, dynamic> toJson() => {
        'birthday': birthday,
        'id' : id,
      };

我的用户模型。

 final user = User(
                    birthday: DateTime.parse(_date.text),

 Future createUser(User user) async {
final docUser = FirebaseFirestore.instance.collection('users').doc();
user.id = docUser.id;

final json = user.toJson();
await docUser.set(json);

}

我试图保存到 Firestore 的地方。

DateTime? pickedDate = await showDatePicker(
                context: context,
                initialDate: DateTime.now(),
                firstDate: DateTime(1900),
                lastDate: DateTime.now());

            if (pickedDate != null) {
              setState(() {
                _date.text = DateFormat('dd-MM-yyyy').format(pickedDate);
              });
            }

我想要用户生日的 dateFormat 表单。

当我按下保存按钮将其保存到数据库时,

FormatException:无效的日期格式 09-08-2012

报错。

【问题讨论】:

    标签: flutter firebase dart google-cloud-firestore


    【解决方案1】:

    看起来您正在使用 DateFormat 类来格式化从 showDatePicker 小部件获取的日期。但是,User 类中的 toJson 方法期望生日字段是一个 DateTime 对象,但您却以 dd-MM-yyyy 的格式传递给它一个 string

    要修复此错误,您可以修改 toJson 方法以接受 string 而不是 DateTime 对象,或者您可以将 string 解析回 DateTime 对象,然后再将其传递给 @987654333 @ 方法。

    这是一个示例,说明如何修改 toJson 方法以接受 string 而不是 DateTime 对象:

    Map<String, dynamic> toJson() => {
      'birthday': DateFormat('dd-MM-yyyy').format(birthday),
      'id' : id,
    };
    

    或者您可以将字符串解析回 DateTime 对象,然后再将其传递给 toJson 方法,如下所示:

    Future createUser(User user) async {
      final docUser = FirebaseFirestore.instance.collection('users').doc();
      user.id = docUser.id;
    
      // Parse the string back into a DateTime object
      final birthday = DateFormat('dd-MM-yyyy').parse(_date.text);
      final json = user.toJson();
      await docUser.set(json);
    }
    

    我希望这有帮助!如果您有任何其他问题,请告诉我。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-01-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-06-07
      • 1970-01-01
      • 2020-08-20
      相关资源
      最近更新 更多