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

Time:09-01

I've had a lot of trouble with the APIs. in this case i want to get data from here: 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

CodePudding user response:

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

CodePudding user response:

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