yorman lopez
yorman lopez

Reputation: 15

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:

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

Upvotes: 0

Views: 212

Answers (2)

eamirho3ein
eamirho3ein

Reputation: 17880

Change this:

final list = data['data']["images"]["jpg"]["image_url"] as List;

to:

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'] as List;
      List images = [];
      list.forEach((element) => images.add(DataApi(image:element["images"]["jpg"]["image_url"])));

      return images;
    } else {
      // If the server did not return a 200 OK response,
      // then throw an exception.
      throw Exception('Failed to load ');
    }
  }

and use it like:

Image.network(lista[index].image);

Upvotes: 1

Josteve Adekanbi
Josteve Adekanbi

Reputation: 12673

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 ');
    }
  }

Upvotes: 0

Related Questions