Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get data from an api and then display it on screen correctly?

I’ve had a lot of trouble with the APIs. in this case i want to get data from here:
https://api.jikan.moe/v4/anime
What I want is to access the images. i tried to do it this way

Future<List<DataApi>> fetchdata() async {
    final response =
        await http.get(Uri.parse('https://api.jikan.moe/v4/anime'));

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);

      final list = data['data']["images"]["jpg"]["image_url"] as List;
      //final list = data['data']["title"] as List;
      return list.map((e) => DataApi(image: e)).toList();
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load ');
    }
  }

I honestly do this based on this: https://docs.flutter.dev/cookbook/networking/fetch-data
but it doesn’t really explain everything.

here the futurebuilder to show the information:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

body: Center(
        child: FutureBuilder<List<DataApi>>(
          future: fetchdata(),
          builder:
              (BuildContext context, AsyncSnapshot<List<DataApi>> snapshot) {
            if (snapshot.hasData) {
              final lista = snapshot.data!;
              return ListView.builder(
                itemCount: lista.length,
                itemBuilder: (BuildContext context, int index) {
                  return Image.network(lista[index].image);
                },
              );
            } else if (snapshot.hasError) {
              return Text("${snapshot.error}");
            } else {
              return const CircularProgressIndicator();
            }
          },
        ),
      ),
    

and here the error and the model.
enter image description here

class DataApi {
  String image;

  DataApi({
    required this.image,
  });

  factory DataApi.fromJson(Map<String, dynamic> json) {
    return DataApi(
      image: json['image_url'],
    );
    /*name: json["name"],
      state: json["status"],
      gender: json["species"]*/

    //List? get results => null;
  }
}


  

I always get similar errors, sometimes it needs a string and I pass it an int etc., which is why as a beginner I would like you to recommend a reading to stop making these types of errors. and the correct way to get data from an api is to store it in a list and iterate through it to display it on the screen. Thanks a lot

>Solution :

Try this:

Future<List<DataApi>> fetchdata() async {
    final response =
        await http.get(Uri.parse('https://api.jikan.moe/v4/anime'));

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);

      final list = data['data'];
      return list.map((e) => DataApi(image: e["images"]["jpg"]["image_url"])).toList();
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load ');
    }
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading