0

Dart version: 2.8.0

I'm getting this: Instance of 'Future<String>' even though I'm using await.

See the code: from loading.dart (this is first page when app launch)

 void setUpWorldTime() async {
    WorldTime worldTime = await WorldTime(location: 'Berlin', flag: 'germany.png', url: 'Asia/Kolkata');
    pri(worldTime.getTime());

  }

  @override
  void initState() {
    super.initState();
    setUpWorldTime();
  }

world_time.dart

import 'dart:convert';

import 'package:http/http.dart';

class WorldTime {
  String location;
  String time;
  String flag;
  String url;

  WorldTime({this.location, this.flag, this.url});

  Future<String> getTime() async {
    print('called getTime()');
    Response response = await get('http://worldtimeapi.org/api/timezone/$url');
    Map data = jsonDecode(response.body);

    String dateTime = data['datetime'];
    String offSet = data['utc_offset'].toString().substring(1, 3);
    DateTime now = DateTime.parse(dateTime);
    now = now.add(Duration(hours: int.parse(offSet)));
    time = now.toString();

    return Future.value(time);
  }
}

Right now, I'm following this: https://www.youtube.com/watch?v=9lCQhwo8WT4&list=PL4cUxeGkcC9jLYyp2Aoh6hcWuxFDX6PBJ&index=28

In above tutorial it is working because that time dart 1.0 was new

The problem in my code is this statement pri(worldTime.getTime()); is executing immediately, before completing API!

Also, please teach me that how to get value, which I tried to return like this: return Future.value(time);

1 Answers1

1

A constructor may only return an instance of the class it creates (WorldTime). Constructors cannot be asynchronouse because they would have to return Future<WorldTime> which is not supported.

In your case you should just create and instance of WorldTime:

WorldTime worldTime = WorldTime(location: 'Berlin', flag: 'germany.png', url: 'Asia/Kolkata');

And then call asynchronous method getTime on it:

print(await worldTime.getTime());
Karol Lisiewicz
  • 654
  • 5
  • 15
  • yes, it's working but you not told, that how I'll get time in this loading activity –  Apr 05 '20 at 21:07
  • String temp = await worldTime.getTime(); setState(() { time = temp; pri(time); }); } –  Apr 05 '20 at 21:08
  • I tried this also: void setUpWorldTime() { WorldTime worldTime = WorldTime(location: 'Berlin', flag: 'germany.png', url: 'Asia/Kolkata'); setState(() async { time = await worldTime.getTime(); pri(time); }); } –  Apr 05 '20 at 21:21
  • Can you help? https://stackoverflow.com/questions/61843230/how-stick-to-with-adapter-position-while-its-scrolling-in-android/ –  May 17 '20 at 14:03