简体   繁体   中英

type 'DateTime' is not a subtype of type 'String' in Flutter Cloud Firestore

I'm trying to get DateTime.now() and write/read it with Cloud FireStore. But got the error

This is my code

Text( 
DateFormat('dd/MM/yyyy kk:mm')
.format(DateTime
.fromMillisecondsSinceEpoch(int.parse(document[index].data['timeCreated']))),
style: timeStyle,
),

Firestore.instance.runTransaction((transaction) async {
      await transaction.set(
        docRef,
        {'timeCreated': DateTime.now().millisecondsSinceEpoch.toString()},
      );
    });

And got this error

I/flutter ( 3378): Another exception was thrown: type 'DateTime' is not a subtype of type 'String'

Convert to string:

int time = DateTime.now().millisecondsSinceEpoch;
String t = "$time";

You can use custom converter functions!, example here

static String _dateTimeToEpochUs(DateTime dateTime) =>
   dateTime?.microsecondsSinceEpoch;

to use

var dateInString =  _dateTimeToEpochUs(DateTime.now())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM