Home > OS >  Project freezes when I try to get data from api
Project freezes when I try to get data from api

Time:04-17

I have created a function which is going to get data from API. But when I open the project nothing is returned to me. I placed two prints before and after getting data, first one is printed but nothing happens after that. I don't get any error.

void getData() async {
    print("----Before");

    Response response = await get(Uri.parse('https://worldtimeapi.org/timezones/Africa/Abidjan'));

    print("----After");
    Map data = jsonDecode(response.body);
    print(data);

  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

CodePudding user response:

Can't see any problem with your code. I tried to run the above code you given. Seems like some problem with the API. And if you're app seems stuck like freezing and if you're using futureBuilder for this function, try using return in your function.

CodePudding user response:

So what is happening is that you are calling getData(); after super.initState(), another thing is that your Url is also wrong.

Here's the correct one,

https://worldtimeapi.org/api/timezone/Africa/Abidjan

And your code should look like this to work properly.

  void getData() async {
    print("----Before");

    Response response = await get(
        Uri.parse('https://worldtimeapi.org/api/timezone/Africa/Abidjan'));

    print("----After");
    Map data = jsonDecode(response.body);
    print(data);
  }

  @override
  void initState() {
    getData();
    super.initState();
    
  } 
  • Related