Home > Back-end >  Fetch data from firestore and firebase storage and displaying in flutter
Fetch data from firestore and firebase storage and displaying in flutter

Time:04-17

I am querying data from firestore and with the data, I am getting the Image data from the firestore. With image information I am getting getdownloadUrl(); The print statement inside the properties.docs.map are not working (What I mean is nothing is working after the data is fetched from firestore), And loading indicator in bloc is always showing.

class FixedCubit extends Cubit<FixedState> {
  FixedCubit() : super(FixedInitial());

  void fetchProperties()async{
    emit(FixedLoading());
    List<UploadModel> upload = [];
    final QuerySnapshot properties =
    await FirebaseRepo.instance.getFixedHomes().get();

    properties.docs.map((e) async {
      print(e.get('uid'));
      print(e.get('pickedFilesName')[0]);

      final String url  = await FirebaseRepo.instance
          .downloadAllUserURLs(e.get('uid'), e.get('pickedFilesName')[0]);
      upload.add(UploadModel.fromMap(e.data() as Map<String, dynamic>,url));
      emit(FixedSuccess(upload));
    });
  }
}

This is my state class

part of 'fixed_cubit.dart';

@immutable
abstract class FixedState {}

class FixedInitial extends FixedState {}

class FixedLoading extends FixedState {}

class FixedSuccess extends FixedState {
  final List<UploadModel> uploadModel;

  FixedSuccess(this.uploadModel);
}

class FixedUnSuccess extends FixedState {
  final String? msg;

  FixedUnSuccess({this.msg});
}

These are the firebase methods

///  =========  Database  Get ========== ///

  Query getFixedHomes() {
    return _firestore
        .collectionGroup('properties')
        .where('preference', isEqualTo: 'Fixed Price')
        .orderBy('createdAt', descending: true);
  }

  Future<String> downloadAllUserURLs(String uid, String image) async {
    return await firebase_storage.FirebaseStorage.instance
        .ref('property/$uid')
        .child(image)
        .getDownloadURL()
        .catchError((onError) {
      print('On FirebaseStorage Exception $onError');
    });
  }

This is Bloc

BlocConsumer<FixedCubit, FixedState>(
          bloc: BlocProvider.of<FixedCubit>(context),
          builder: (context, state) {
            if (state is FixedLoading) {
              return Center(child: getCircularProgress());
            } else if (state is FixedSuccess) {
              return SizedBox(
                height: 300.0,
                child: ListView.builder(
                  physics: const BouncingScrollPhysics(),
                  scrollDirection: Axis.horizontal,
                  itemCount: state.uploadModel.length,
                  itemBuilder: (BuildContext context, int index) {
                    final value = state.uploadModel[index];

                    print(
                        'File name ${state.uploadModel[index].pickedFilesName}');
                    print(state.uploadModel[index].pickedFilesName?[0]);

                    return GestureDetector(
                      onTap: () {
                        Navigator.of(context).pushNamed(
                            Routes.fixedDetails,
                            arguments: value.thumbnail);
                      },
                      child: CustomFixed(
                          image: value.thumbnail.toString(),
                          city: value.city.toString(),
                          startPrice: value.startPrice.toString(),
                          endPrice: value.endPrice.toString(),
                          title: value.title.toString()),
                    );
                  },
                ),
              );
            } else {
              return const Text('Something went wrong');
            }
          },
          listener: (context, state) {}),

CodePudding user response:

Update use for loop instead of map() function

for (var e in properties.docs) {
      final String url = await FirebaseRepo.instance
          .downloadAllUserURLs(e.get('uid'), e.get('pickedFilesName')[0]);
      upload.add(UploadModel.fromMap(e.data() as Map<String, dynamic>, url));
    }
  • Related