Home > Back-end >  I need to create a carousel slider using the data fetch from firebase. i have tried a lots of method
I need to create a carousel slider using the data fetch from firebase. i have tried a lots of method

Time:12-20

This is the firebase database structure that I am using:

----- database image ----

import 'package:awesome_dropdown/awesome_dropdown.dart';
import 'package:carousel_slider/carousel_controller.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:hexated/Refactored/widgets/headings.dart';
import 'package:smooth_page_indicator/smooth_page_indicator.dart';

import '../Refactored/sections/bottomNavigation.dart';
import '../Refactored/sections/todaysMealContainer.dart';
import '../Refactored/widgets/mealDayList.dart';

class messDiary extends StatefulWidget {
  messDiary({Key? key}) : super(key: key) {}

  // late String whatIsToday = DateFormat('EEEE').format(DateTime.now());

  @override
  State<messDiary> createState() => _messDiaryState();
}

class _messDiaryState extends State<messDiary> {
  int activeIndex = 0;
  final carouselController = CarouselController();
  String valueChoose = 'Select a day';
  var itemName;

  final CollectionReference _collectData =
      FirebaseFirestore.instance.collection('messdiary');
  late Stream<QuerySnapshot> _streamCollect;

  @override
  void initState() {
    super.initState();
    _streamCollect = _collectData.snapshots();
  }

  @override
  Widget build(BuildContext context) {
    double height = MediaQuery.of(context).size.height;
    double width = MediaQuery.of(context).size.width;
   
    return Scaffold(
      backgroundColor: const Color(0xFF000000),
      appBar: AppBar(
        backgroundColor: const Color(0xFF000000),
        elevation: 0,
      ),
      bottomNavigationBar: const bottomNavigation(),
      body: ListView(
        children: [
          Column(
            children: [
              headings(headingText: "Today's meals"),
              const SizedBox(
                height: 15,
              ),
              StreamBuilder<QuerySnapshot>(
                  stream: _streamCollect,
                  builder: (context, AsyncSnapshot<QuerySnapshot> snapshot) {
                    if (!snapshot.hasData) {
                      return const Center(
                        child: CircularProgressIndicator(),
                      );
                    }
                    List<DocumentSnapshot> snaps = snapshot.data!.docs;
                    return CarouselSlider(
                      options: CarouselOptions(
                        height: height * 0.38,
                        aspectRatio: 2.0,
                        autoPlayCurve: Curves.easeInOutQuart,
                        pauseAutoPlayOnTouch: true,
                        enlargeCenterPage: true,
                        enableInfiniteScroll: false,
                        initialPage: 2,
                        autoPlay: true,
                        onPageChanged: (index, reason) {
                          setState(() {
                            activeIndex = index;
                          });
                        },
                      ),
                      items: snaps.map((e) {
                        return Builder(builder: (BuildContext context) {
                          return todaysMeal(
                              itemName: e['title'],
                              itemImage: e['image'],
                              time: e['time'],
                              dayTime: e['daytime']);
                        });
                      }).toList(),
                    );
                  }),
              const SizedBox(
                height: 15,
              ),
              AnimatedSmoothIndicator(
                onDotClicked: animateToSlide,
                effect: const ExpandingDotsEffect(
                    dotWidth: 14,
                    dotHeight: 14,
                    activeDotColor: Color(0xFF6A7086),
                    dotColor: Color(0xFF2B2E3F)),
                activeIndex: activeIndex,
                count: 4,
              ),
       
        ],
      ),
    );
  }

}

When i try to run the code this error message appears

======== Exception caught by widgets library ======================================================= The following StateError was thrown building Builder(dirty):

Bad state: field does not exist within the DocumentSnapshotPlatform

If it is not the way to access the data then how??

i have tried to the end and tired please help me to fix this issue!!

CodePudding user response:

The field names are 'sunday', 'monday', and so on. Each of these fields has an array of [todaysMeal] jsons, in a manner of speaking.

What you are trying to access are the fields inside each array element.

So what's happening is: you are looking for json keys 'title', 'image', 'daytime', and 'time', but the document snapshot has these keys: 'sunday', 'monday', etc.

I don't think I worded this answer very well, but I hope this was enough to clear up your confusion.


I am replying to your comments here. Here are the code changes that you can try.

// First of all change the don't use the CollectionReference for 'messdiary'.
// final CollectionReference _collectData = FirebaseFirestore.instance.collection('messdiary');
// Use the DocumentReference for 'days'.
final DocumentReference _daysData =
  FirebaseFirestore.instance.collection('messdiary').doc('days');

Then:-

// Change the following statement.
// List<DocumentSnapshot> snaps = snapshot.data!.docs;
// to this:
final daysObj = snapshot.data()!;
final sundayMeals = daysObj["sunday"]
  .map((e)=>todaysMeal(itemName: e['title'], itemImage: e['image'], time: e['time'], dayTime: e['daytime']))
  .toList();
final mondayMeals = ...
...
final saturdayMeals = ...
final mealsData = [...sundayMeals, ...mondayMeals, ....... , ...saturdayMeals];
// Now use mealsData for your carousel.

This code might not work entirely as you expected. You have to do any further debugging.

And if you need further help, I might have to charge you

  • Related