Home > Mobile >  How to get image from API to Carousel in Flutter
How to get image from API to Carousel in Flutter

Time:10-06

I am facing this problem where I am trying to display images in a carousel. I am using the package carousel_slider: ^4.1.1. I am confused because when I hard code the content in a variable it is working perfectly displayed in my carousel widget. but the output is empty I want to use a Carousel in Flutter, so I tried to get it following the code. after running my code it's empty in output.

Map mapResponse = {};
Map dataResponse = {};
List listResponse = {} as List;

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

 @override
 State<apipro> createState() => _apipro();
}

class _apipro extends State<apipro> {
 Future<List> team() async {
   http.Response response;
   response = await http.get(Uri.parse(
       "https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
   // ignore: unnecessary_null_comparison

   Map mapResponse = json.decode(response.body);
   return mapResponse['data'] as List;
 }

 @override
 void initState() {
   // team();
   super.initState();
 }

 @override
 Widget build(BuildContext context) {
   return Center(
     child: FutureBuilder<List?>(
         future: team(),
         builder: (context, snapshot) {
           switch (snapshot.connectionState) {
             case ConnectionState.waiting:
               return const Text(
                 'Loading....',
                 style: TextStyle(
                   fontSize: 16,
                   fontWeight: FontWeight.w100,
                 ),
               );
             default:
               if (snapshot.hasError) {
                 return Text('Error: ${snapshot.error}');
               } else {
                 List data = snapshot.data ?? [];
                 _buildItem(image, String name) {
                   return CarouselSlider(
                     options: CarouselOptions(
                         viewportFraction: 0.3,
                         autoPlayAnimationDuration:
                             const Duration(milliseconds: 2000),
                         autoPlay: true,
                         enlargeCenterPage: true,
                         height: 80),
                     items: <Widget>[
                       for (var i = 0; i < image.length; i  )
                         Container(
                           margin:
                               const EdgeInsets.only(top: 20.0, left: 20.0),
                           decoration: BoxDecoration(
                             image: DecorationImage(
                               image: NetworkImage(image[i]),
                               fit: BoxFit.fitHeight,
                             ),
                             // border:
                             //     Border.all(color: Theme.of(context).accentColor),
                             borderRadius: BorderRadius.circular(32.0),
                           ),
                         ),
                     ],
                   );

                   // ignore: dead_code
                 }

                 return ListView.builder(
                   shrinkWrap: true,
                   padding: const EdgeInsets.all(18),
                   itemBuilder: (context, index) {
                     return _buildItem(data[index]['name']?.toString() ?? '',
                         data[index]['image']?.toString() ?? '');
                   },
                   itemCount: data.length,
                 );
               }
           }
         }),
   );
 }
}

I got the Proper response by Function which I created there is no error in my code. So how i can display Images in carousel_slider? Please Help. Thank you.

CodePudding user response:

class APIPRO extends StatelessWidget {
  const APIPRO({Key? key}) : super(key: key);

  Future<List> team() async {
    http.Response response;
    response = await http.get(Uri.parse("https://www.archmage.lk/api/v1/webapi/getclients?page=0&limit=10"));
    // ignore: unnecessary_null_comparison

    Map mapResponse = jsonDecode(response.body);
    return mapResponse['data'] as List;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder(
            future: team(),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return const Text(
                    'Loading....',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w100,
                    ),
                  );
                default:
                  if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    List data = snapshot.data ?? [];

                    return CarouselSlider(
                        options: CarouselOptions(viewportFraction: 0.3, autoPlayAnimationDuration: const Duration(milliseconds: 2000), autoPlay: true, enlargeCenterPage: true, height: 80),
                        items: data
                            .map(
                              (e) => Container(
                                margin: const EdgeInsets.only(top: 20.0, left: 20.0),
                                decoration: BoxDecoration(
                                  image: DecorationImage(
                                    image: NetworkImage(e["image"]),
                                    fit: BoxFit.fitHeight,
                                  ),
                                  // border:
                                  //     Border.all(color: Theme.of(context).accentColor),
                                  borderRadius: BorderRadius.circular(32.0),
                                ),
                              ),
                            )
                            .toList());
                  }
              }
            }),
      ),
    );
  }
}

enter image description here

CodePudding user response:

Try this:

Center(
        child: FutureBuilder<List?>(
            future: team(),
            builder: (context, snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.waiting:
                  return const Text(
                    'Loading....',
                    style: TextStyle(
                      fontSize: 16,
                      fontWeight: FontWeight.w100,
                    ),
                  );
                default:
                  if (snapshot.hasError) {
                    return Text('Error: ${snapshot.error}');
                  } else {
                    List data = snapshot.data ?? [];

                    return CarouselSlider.builder(
                      itemBuilder: (context, index, realIndex) {
                        return Container(
                          margin: const EdgeInsets.only(top: 20.0, left: 20.0),
                          decoration: BoxDecoration(
                            image: DecorationImage(
                              image: NetworkImage(data[index]['image']),
                              fit: BoxFit.fitHeight,
                            ),
                            color: Colors.red,
                            borderRadius: BorderRadius.circular(32.0),
                          ),
                        );
                      },
                      options: CarouselOptions(
                          viewportFraction: 0.3,
                          autoPlayAnimationDuration:
                              const Duration(milliseconds: 2000),
                          autoPlay: true,
                          enlargeCenterPage: true,
                          height: 80),
                      itemCount: data.length,
                    );
                  }
              }
            }),
      )
  • Related