草庐IT

firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime'

coder 2023-07-23 原文

我正在为我和我的团队正在开发的应用程序寻求帮助。数周以来,我们一直面临以下问题:

flutter type 'Timestamp' is not a subtype of type 'DateTime'

我们想从 Cloud Firestore 获取这些用户数据:

  • 出生[日期时间]
  • 性别[字符串]
  • 许可[日期时间]
  • 姓名[字符串]
  • 大小[字符串]
  • 重量[字符串]

只有birthlicense 在 Cloud Firestore 中存储为 1681720252,因此我们将这些数据解析为 [DateTime]。

这是获取用户数据的代码:

import 'package:cloud_firestore/cloud_firestore.dart';

class User{
  final String _name;
  final String _gender; // 'homme' or 'femme' or 'autre'
  final DateTime _birth;
  final DateTime _license;
  final double _weight;
  final int _size;
  DocumentReference ref;

  User(this._birth,this._gender,this._license,this._name,this._size,this._weight,this.ref);

  User.fromMap(Map<String, dynamic> map, {this.ref})
      : assert(map['name'] != null && map['gender'] != null && map['birth'] != null && map['weight'] != null && map['size'] != null),
        _name = map['name'],
        _gender = map['gender'],
        _birth = map['birth'] as DateTime,
        _license = map['license'] as DateTime,
        _weight = double.parse(map['weight']),
        _size = int.parse(map['size']);

  User.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, ref: snapshot.reference);

  String get name => _name;
  String get gender => _gender;
  DateTime get birth => _birth;
  DateTime get license => _license;
  double get weight => _weight;
  int get size => _size;
}

这里是我们调用这些函数的地方,也是问题似乎出现的地方:

import 'package:bappsalcolit/pages/homepage.dart';
import 'package:flutter/material.dart';
import 'package:bappsalcolit/sign_in/auth.dart';
import 'package:bappsalcolit/sign_in/log_page.dart';
import 'package:bappsalcolit/ads_display.dart';
import 'package:bappsalcolit/dbase/model/global_info.dart';

import 'package:cloud_firestore/cloud_firestore.dart';

User currentUser = User(null, null, null, null, null, null, null);

class RootPage extends StatefulWidget {
  RootPage({this.auth});

  final AuthImpl auth;

  @override
  State<StatefulWidget> createState() => new _RootPageState();
}

enum AuthStatus {
  NOT_DETERMINED,
  NOT_SIGNED_IN,
  SIGNED_IN,
}

class _RootPageState extends State<RootPage> {
  AuthStatus authStatus = AuthStatus.NOT_DETERMINED;
  String _userID = "";

  @override
  void initState(){
    super.initState();
    Ads.hideBanner();
    widget.auth.getCurrentUser().then((user) {
      setState(() {
        if(user != null) {
          _userID = user?.uid;
        }
        authStatus =
        user?.uid == null ? AuthStatus.NOT_SIGNED_IN : AuthStatus.SIGNED_IN;
      });
    });
  }

  void _signedIn() {
    widget.auth.getCurrentUser().then((user){
      setState(() {
        _userID = user?.uid.toString();
      });
    });
    setState(() {
      authStatus = AuthStatus.SIGNED_IN;
    });
  }

  void _signedOut() {
    setState(() {
      authStatus = AuthStatus.NOT_SIGNED_IN;
      _userID = "";
    });
  }

  Widget _buildWaitingScreen() {
    return Scaffold(
      body: Container(
        height: 20.0,
        width: 20.0,
        alignment: Alignment.center,
        child: CircularProgressIndicator(),
      ),
    );
  }

  //========== Here's where the problem seems to appear ==========\\
  gettingSnapshots(){
    Firestore db = Firestore.instance;
    DocumentSnapshot userDS;
    db.collection('users').document(_userID).snapshots().listen((ds) async{
      if (ds.exists) {
        userDS = await db.collection('users').document(_userID).get();
        try {
          currentUser = User.fromSnapshot(userDS);
        } catch (e) {
          print('Error 1131: $e');
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    switch (authStatus) {
      case AuthStatus.NOT_SIGNED_IN:
        return new SignIn(
          auth: widget.auth,
          onSignedIn: _signedIn,
        );
        break;
      case AuthStatus.SIGNED_IN:
        if(_userID.length > 0 && _userID != null) {
          gettingSnapshots();
          return new HomePage(
            userID: _userID,
            auth: widget.auth,
            onSignedOut: _signedOut,
          );
        }
        break;
      case AuthStatus.NOT_DETERMINED:
        return _buildWaitingScreen();
        break;
    }
    return _buildWaitingScreen();
  }
}

此问题仅出现在 iOS 上。在 Android 上一切正常。

问题应该不是来自 Cloud Firestore 和应用程序之间的链接,因为我们可以获取其他存储的信息。

最佳答案

在我的项目中我使用

birth: parsedJson['birth'].toDate()

而且效果很好,这是另一种选择。

关于firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55170087/

有关firebase - flutter 问题 : type 'Timestamp' is not a subtype of type 'DateTime'的更多相关文章

  1. ruby-on-rails - rails : "missing partial" when calling 'render' in RSpec test - 2

    我正在尝试测试是否存在表单。我是Rails新手。我的new.html.erb_spec.rb文件的内容是:require'spec_helper'describe"messages/new.html.erb"doit"shouldrendertheform"dorender'/messages/new.html.erb'reponse.shouldhave_form_putting_to(@message)with_submit_buttonendendView本身,new.html.erb,有代码:当我运行rspec时,它失败了:1)messages/new.html.erbshou

  2. ruby-on-rails - 'compass watch' 是如何工作的/它是如何与 rails 一起使用的 - 2

    我在我的项目目录中完成了compasscreate.和compassinitrails。几个问题:我已将我的.sass文件放在public/stylesheets中。这是放置它们的正确位置吗?当我运行compasswatch时,它不会自动编译这些.sass文件。我必须手动指定文件:compasswatchpublic/stylesheets/myfile.sass等。如何让它自动运行?文件ie.css、print.css和screen.css已放在stylesheets/compiled。如何在编译后不让它们重新出现的情况下删除它们?我自己编译的.sass文件编译成compiled/t

  3. ruby - 在 64 位 Snow Leopard 上使用 rvm、postgres 9.0、ruby 1.9.2-p136 安装 pg gem 时出现问题 - 2

    我想为Heroku构建一个Rails3应用程序。他们使用Postgres作为他们的数据库,所以我通过MacPorts安装了postgres9.0。现在我需要一个postgresgem并且共识是出于性能原因你想要pggem。但是我对我得到的错误感到非常困惑当我尝试在rvm下通过geminstall安装pg时。我已经非常明确地指定了所有postgres目录的位置可以找到但仍然无法完成安装:$envARCHFLAGS='-archx86_64'geminstallpg--\--with-pg-config=/opt/local/var/db/postgresql90/defaultdb/po

  4. ruby - 通过 rvm 升级 ruby​​gems 的问题 - 2

    尝试通过RVM将RubyGems升级到版本1.8.10并出现此错误:$rvmrubygemslatestRemovingoldRubygemsfiles...Installingrubygems-1.8.10forruby-1.9.2-p180...ERROR:Errorrunning'GEM_PATH="/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/ruby-1.9.2-p180@global:/Users/foo/.rvm/gems/ruby-1.9.2-p180:/Users/foo/.rvm/gems/rub

  5. ruby-on-rails - Rails 3 I18 : translation missing: da. datetime.distance_in_words.about_x_hours - 2

    我看到这个错误:translationmissing:da.datetime.distance_in_words.about_x_hours我的语言环境文件:http://pastie.org/2944890我的看法:我已将其添加到我的application.rb中:config.i18n.load_path+=Dir[Rails.root.join('my','locales','*.{rb,yml}').to_s]config.i18n.default_locale=:da如果我删除I18配置,帮助程序会处理英语。更新:我在config/enviorments/devolpment

  6. ruby-on-rails - Rails 3.2.1 中 ActionMailer 中的未定义方法 'default_content_type=' - 2

    我在我的项目中添加了一个系统来重置用户密码并通过电子邮件将密码发送给他,以防他忘记密码。昨天它运行良好(当我实现它时)。当我今天尝试启动服务器时,出现以下错误。=>BootingWEBrick=>Rails3.2.1applicationstartingindevelopmentonhttp://0.0.0.0:3000=>Callwith-dtodetach=>Ctrl-CtoshutdownserverExiting/Users/vinayshenoy/.rvm/gems/ruby-1.9.3-p0/gems/actionmailer-3.2.1/lib/action_mailer

  7. ruby - 在 jRuby 中使用 'fork' 生成进程的替代方案? - 2

    在MRIRuby中我可以这样做:deftransferinternal_server=self.init_serverpid=forkdointernal_server.runend#Maketheserverprocessrunindependently.Process.detach(pid)internal_client=self.init_client#Dootherstuffwithconnectingtointernal_server...internal_client.post('somedata')ensure#KillserverProcess.kill('KILL',

  8. ruby - 主要 :Object when running build from sublime 的未定义方法 `require_relative' - 2

    我已经从我的命令行中获得了一切,所以我可以运行rubymyfile并且它可以正常工作。但是当我尝试从sublime中运行它时,我得到了undefinedmethod`require_relative'formain:Object有人知道我的sublime设置中缺少什么吗?我正在使用OSX并安装了rvm。 最佳答案 或者,您可以只使用“require”,它应该可以正常工作。我认为“require_relative”仅适用于ruby​​1.9+ 关于ruby-主要:Objectwhenrun

  9. ruby - 无法让 RSpec 工作—— 'require' : cannot load such file - 2

    我花了三天的时间用头撞墙,试图弄清楚为什么简单的“rake”不能通过我的规范文件。如果您遇到这种情况:任何文件夹路径中都不要有空格!。严重地。事实上,从现在开始,您命名的任何内容都没有空格。这是我的控制台输出:(在/Users/*****/Desktop/LearningRuby/learn_ruby)$rake/Users/*******/Desktop/LearningRuby/learn_ruby/00_hello/hello_spec.rb:116:in`require':cannotloadsuchfile--hello(LoadError) 最佳

  10. ruby - 通过 RVM (OSX Mountain Lion) 安装 Ruby 2.0.0-p247 时遇到问题 - 2

    我的最终目标是安装当前版本的RubyonRails。我在OSXMountainLion上运行。到目前为止,这是我的过程:已安装的RVM$\curl-Lhttps://get.rvm.io|bash-sstable检查已知(我假设已批准)安装$rvmlistknown我看到当前的稳定版本可用[ruby-]2.0.0[-p247]输入命令安装$rvminstall2.0.0-p247注意:我也试过这些安装命令$rvminstallruby-2.0.0-p247$rvminstallruby=2.0.0-p247我很快就无处可去了。结果:$rvminstall2.0.0-p247Search

随机推荐