Home > Back-end >  List of data from http.get not returning to calling screen in Dart
List of data from http.get not returning to calling screen in Dart

Time:07-01

I have a 'http.get' class like this in Dart

import 'dart:convert' as convert;

import 'dart:async';

import 'package:http/http.dart' as http;

class Networking {
  late Uri url;

  Map<dynamic, dynamic> jsonResponse = {};

  Networking({required this.url});

  List<String> listOfUrls = [];

  Future<List<String>> getRawWeatherData() async {
    http.Response response = await http.get(url);
    Map data = convert.jsonDecode(response.body);
    data.remove("schema");
    print("data $data");
    print("data in networking.dart - ${data["data"]}");
    var x = data["data"];
    int count = 0;
    for (var element in x) {
      count  ;
    }

    for (int i = 0; i < count; i  ) {
      listOfUrls.add(data["data"][i]["uri"]);
    }
    print("list in networking - $listOfUrls");

    return listOfUrls;
  }
}

This above class prints out the correct data List built from the Map, from http.get.

Now I call this getRawWeatherData method from a stateful widget class as follows

Future<List<String>> getRawData()  {
    Networking networking = Networking(url: url);
    Future<List<String>> rawData =  networking.getRawWeatherData() ;

    print("rawData in getRawData is $rawData");
    return rawData;
  }

But the print in the getRawData() method does not print any data.

Where is the problem ?

CodePudding user response:

You have to await the call to getRawWheatherData()

List<String> rawData = await networking.getRawWeatherData();

CodePudding user response:

You can call this way :

Future<List<String>> getRawData()  async {
    Networking networking = Networking(url: url);
    Future<List<String>> rawData =  await networking.getRawWeatherData();

    print("rawData in getRawData is $rawData");
    return rawData;
  }

You have to write await while calling that api request and add async to calling method

  • Related