FutureBuilder not working in Carousel Flutter Firebase

Viewed 98

I am trying to show a carousel where the images are fetched from Firebase Realtime Database.

The problem is that unless I do a Hot Restart , the images doesn't appear in the slider.

This is my code to getData from Firebase:

    Future getData() async {
    var databaseRef2 = FirebaseDatabase.instance.reference();
    databaseRef2 = FirebaseDatabase.instance.reference().child("Sliders");
    databaseRef2.once().then((DataSnapshot snapshot) {
      Map<dynamic, dynamic> values = snapshot.value;
      values.forEach((key, values) {
        imgList.add(values["img"]);
      });
    });
    return imgList;
  }

This is my Slider code:

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("My App"),
      ),
      body: Column(
        children: [
          FutureBuilder(
            future: getData(),
            builder: (context, snapshot) {
              if (snapshot.hasData) {
                return CarouselSlider(
                  options: CarouselOptions(
                    height: 180.0,
                    enlargeCenterPage: true,
                    autoPlay: true,
                    aspectRatio: 16 / 9,
                    autoPlayCurve: Curves.easeInBack,
                    enableInfiniteScroll: true,
                    autoPlayAnimationDuration: Duration(milliseconds: 900),
                    viewportFraction: 0.8,
                  ),
                  items: imgList.map((e) {
                    return Container(
                      margin: EdgeInsets.all(6.0),
                      decoration: BoxDecoration(
                        borderRadius: BorderRadius.circular(8.0),
                      ),
                      child: Image.network(
                        e,
                        fit: BoxFit.fill,
                      ),
                    );
                  }).toList(),
                );
              } else {
                return CircularProgressIndicator();
              }
            },
          ),
            ),
          ),
          

I am a newbie to Flutter.

1 Answers

Try using this way.

Future<List<String>> getData() async {
    var databaseRef2 = FirebaseDatabase.instance.reference();
    databaseRef2 = FirebaseDatabase.instance.reference().child("Sliders");
    DatabaseEvent event = await databaseRef2.once();
    Map<dynamic, dynamic> values =
        event.snapshot.value as Map<dynamic, dynamic>;
    values.forEach((key, values) {
      imgList.add(values["img"]);
    });
    return imgList;
  }

////

FutureBuilder<List<String>>(
     future: getData(),
Related