Home > Back-end >  type 'Future<DateTime>' is not a subtype of type 'DateTime'
type 'Future<DateTime>' is not a subtype of type 'DateTime'

Time:12-03

In my Flutter app I'm fetching some datetime info from an API but getting this error. I'm using Provider.

My display widget has this in didChangeDependencies:

_userDateTime = Provider.of<TimeZones>(context, listen: false).getDateTime(0);
print('didChangeDependencies()');
print(_localDateTime.toString());
print(DateFormat("E d MMM hh:mm a").format(_localDateTime));

and this outputs ok up until I try to use that datetime object.

flutter: didChangeDependencies()
flutter: Instance of 'Future<DateTime>'

======== Exception caught by widgets library 

So I know that TimeZones is returning a DateTime object, I can test the values and see that it's right.

How do I get my widget to accept the Future and treat it as a normal DateTime?

or is there a better approach?

CodePudding user response:

Add async to the didChangeDependencies function and await for the getDatetime result like this:

_userDateTime = await Provider.of<TimeZones>(context, listen: false).getDateTime(0);

CodePudding user response:

It looks like your getDateTime(0) call returns a future. Try to await it:

_userDateTime = await Provider.of<TimeZones>(context, listen: false).getDateTime(0);

CodePudding user response:

In didChangeDependencies I changed the provider request to

Provider.of<TimeZones>(context, listen: false)
          .setDateTime(-1, 0)
          .then((_)

and in my builder I call

final tzData = Provider.of<TimeZones>(context);
    DateTime _localDateTime = tzData.getDateTime(-1);
    DateTime _userDateTime = tzData.getDateTime(0);

and it seems to work as expected. More testing needed.

  • Related