Home > front end >  How to create and iterate a list with images from an api?
How to create and iterate a list with images from an api?

Time:08-12

Im consuming the rick and morty api, I want to create a list to save the images then loop through them and display them on the screen.

import 'package:apirick/models/dataapi.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:flutter/material.dart';
// ignore: unused_import
import 'dart:convert';

// ignore: unused_import
import 'package:http/http.dart' as http;

class Api extends StatefulWidget {
  const Api({Key? key}) : super(key: key);

  @override
  State<Api> createState() => _ApiState();
}

class _ApiState extends State<Api> {
  Future<DataApi> fetchapi() async {
    final response =
        await http.get(Uri.parse('https://rickandmortyapi.com/api/character'));
    // Appropriate action depending upon the
    // server response
    if (response.statusCode == 200) {
      return DataApi.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load album');
    }
  }

  @override
  Widget build(BuildContext context) {
    return FutureBuilder<DataApi>(
      future: fetchapi(),
      builder: (BuildContext context, AsyncSnapshot<DataApi> snapshot) {
        if (snapshot.hasData) {
          final list = snapshot.data!;

          return CarouselSlider.builder(
            itemCount: list.length,
            itemBuilder: (BuildContext context, int index) {
              return Container(
                child: Center(
                  child: NetworkImage(list[index].image),

                ),
              );
            },

As you can see, I created a list to get the values ​​and I wanted to iterate through it to render the images.

CodePudding user response:

I recommend you use

 Column(children: [
   ...listImages.map((l) => showImage(context, l)),
 ]),

CodePudding user response:

You could get the images all in the async function, or even a separate one. After if (response.statusCode == 200) try returning a List of images?

List<Image> images = [];
var responseData = json.decode(response.body);
for (var imageUrl in responseData) {
     images.add(Image.network("$images["image"]");
}
return images;

This code is untested and where we may run into issues is the for loop not waiting for the Image.network call to resolve.

CodePudding user response:

There's some issues in your code i have fixed and complete the code with some extra validation checks. Now it is working as expected

import 'package:carousel_slider/carousel_slider.dart';
import 'package:apirick/models/dataapi.dart';
import 'package:flutter/material.dart';
import 'dart:convert';

import 'package:http/http.dart' as http;

class Api extends StatefulWidget {
  const Api({Key? key}) : super(key: key);

  @override
  State<Api> createState() => _ApiState();
}

class _ApiState extends State<Api> {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: FutureBuilder<DataApi>(
        future: fetchapi(),
        builder: (BuildContext context, AsyncSnapshot<DataApi> snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data != null) {
              final List<Results>? list = snapshot.data!.results;
              if (list != null && list.isNotEmpty) {
                return CarouselSlider.builder(
                  itemCount: list.length,
                  options: CarouselOptions(
                    aspectRatio: 2.0,
                    autoPlay: true,
                    enlargeCenterPage: true,
                    viewportFraction: 0.9,
                    onPageChanged: (index, reason) {},
                  ),
                  itemBuilder:
                      (BuildContext context, int index, int pageIndex) {
                    return Container(
                      child: Center(
                        child: Image.network(list[index].image ?? ''),
                      ),
                    );
                  },
                );
              } else {
                return const Text('No Data');
              }
            } else {
              return const Text('No Data');
            }
          } else {
            return const CircularProgressIndicator();
          }
        },
      ),
    );
  }

  Future<DataApi> fetchapi() async {
    final response =
        await http.get(Uri.parse('https://rickandmortyapi.com/api/character'));
    // Appropriate action depending upon the
    // server response
    if (response.statusCode == 200) {
      return DataApi.fromJson(json.decode(response.body));
    } else {
      throw Exception('Failed to load album');
    }
  }
}
  • Related