Home > database >  Extract list from a Future Flutter
Extract list from a Future Flutter

Time:11-08

I have a future, that returns a Future response.

class FutureInformation extends StatelessWidget {

  const FutureInformation({Key? key}) : super(key: key);

 Future<List<SliderDetails>> getSliderDetails() async {
    try {
      var response = await http.get((Uri.parse("/path/to/jsonFile.json")));
          if (response.statusCode == 200) {
            print(response.statusCode);
            var jsonData = json.decode(utf8.decode(response.bodyBytes));

      List<SliderDetails> listedFestivals = [];

      for (var map in jsonData) {

     SliderDetails allFestivals = SliderDetails(
     map['urlLink'] ?? "",
     map['name'] ?? "",
   );

  /// add them to the array
  listedFestivals.add(allFestivals);
  }
    return listedFestivals;
  }
  } catch (e){      
    print(e);
  }
      throw Exception('Nothing here, no food');
    }

my Json file only has 2 elements both strings

[{
  "image": "https://i.gyazo.com/5d808c6e55a8b2151974bf53b35e21b6.png",
  "title": "Yellow Car"
},
  {
    "image": "https://i.gyazo.com/7f33e4e78a54d1c4795aec5e0d57fab1.png",
    "title": "Black Car"
  },
  {
    "image": "https://i.gyazo.com/5e399b0ac1ffca12165f51af8bc3e81a.png",
    "title": "Blue Car"
  },
  {
    "image": "https://i.gyazo.com/8c74b2ec4da1ba477afbc67111573c4d.png",
    "title": "Vintage Car"
  }

]

From the response I want to create 2 different lists that would look like the example I have below.

final List<String> imgList = [
     "https://i.gyazo.com/5d808c6e55a8b2151974bf53b35e21b6.png",
      "https://i.gyazo.com/7f33e4e78a54d1c4795aec5e0d57fab1.png",
      "https://i.gyazo.com/5e399b0ac1ffca12165f51af8bc3e81a.png",
      "https://i.gyazo.com/8c74b2ec4da1ba477afbc67111573c4d.png",        

    ];

final List<String> titlesList = [
      "Yellow Car",
      "Black Car",
      "Blue Car",
      "Vintage Car",
      
    ];

The response I get is

Instance of 'Future<List<SliderDetails>>'

And what I want to know how can I split the future into 2 separate lists, thanks for any help.

This is how I am calling the Future

var datasource = const FutureInformation();

    getSliderDetailsEvents() async {
      List futureEvents = await datasource.getSliderDetails();
      return futureEvents ;
    }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

CodePudding user response:

At first change your SliderDetails model to this:

class SliderDetails {
  final List<String> links;
  final List<String> names;
  SliderDetails({required this.links, required this.names});
}

then change your getSliderDetails to this:

Future<SliderDetails> getSliderDetails() async {
    try {
      var response = await http.get((Uri.parse("/path/to/jsonFile.json")));
      if (response.statusCode == 200) {
        print(response.statusCode);
        var jsonData = json.decode(utf8.decode(response.bodyBytes));

        List<String> urlLinks = [];
        List<String> names = [];

        for (var map in jsonData) {
          urlLinks.add(map['urlLink'] ?? "");
          names.add(map['name'] ?? "");
        }
        return SliderDetails(
          links: urlLinks,
          names:names,
        );
      }
    } catch (e) {
      print(e);
    }
    throw Exception('Nothing here, no food');
  }

now you can use it like this:

getSliderDetailsEvents() async {
  SliderDetails futureEvents = await datasource.getSliderDetails();
  
  print("links:${futureEvents.links}");
  print("links:${futureEvents.names}");
}

CodePudding user response:

For now you can receive a Future<List<SliderDetails>> because you are now awaiting the response from your Future method.

So you should add the keywords await and async to await the response from your Future method. (In you case probably a missing await in getSliderDetails).
That will give you a List<SliderDetails> instead of a Future<List<SliderDetails>>

To separate your current List<SliderDetails> into two separate List You can use multiple methods to iterate on your list and add some logic.

I recommend using the map method on List.

    final List<String> imageList = futureEvents.map((e) => e["image"]).toList();
    final List<String> titleList = futureEvents.map((e) => e["title"]).toList();
  • Related