How to get List from future list function in Dart

Issue

I’m creating an app that use assets_audio_player to play music from a json response that are generated from a php script. There is a Future list function that return an Audio list. Audio isn’t a Widget so i can’t use a FutureBuilder. How can i use the future list?

    Future<List<Audio>> creaLista() async {
      final response = await http.post(Uri.parse(url));
      String responseBody = response.body;

      dynamic jsonObject = json.decode(responseBody);

      final convertedJsonObject = jsonObject.cast<Map<String, dynamic>>();

      List<Song> list =
          convertedJsonObject.map<Song>((json) => Song.fromJson(json)).toList();

      List<Audio> audioList = list
          .map<Audio>((json) => Audio.network(
                urlSong + json.url,
                metas: Metas(
                  title: json.title,
                  artist: json.artist,
                  album: json.album,
                  image: MetasImage.network(
                    urlImage + json.image,
          ),
        ),
      ))
    .toList();
  

    return audioList;
    }

Solution

You don’t need the Future to return a Widget to use FutureBuilder. You can create widgets based on the returned results of the future. Here’s an example that would display the just the artist, but it should give you the idea.

In general I would suggest creating a custom Widget that takes an Audio object and displays all of the Audio data how you would like.

FutureBuilder(
          future: creaLista(),
          builder: (context, snapshot) {
            if (snapshot.hasData) {
              final audioList = snapshot.data as List<Audio>;
              return ListView.builder(
                  itemCount: audioList.length,
                  itemBuilder: (context, index) {
                    return Text(audioList[index].artist);
                  });
            } else if (snapshot.hasError) {
              // handle error here
              return Text('${snapshot.error}');
            } else {
              return CircularProgressIndicator(); // displays while loading data
            }
          },
        )

This assumes your Audio class looks like this

class Audio {
  String title, artist, album;
  Audio(this.title, this.artist, this.album);
}

I’m sure its more complex than that but it should give you the idea.

Answered By – Loren.A

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published