zakiblacki
zakiblacki

Reputation: 233

How to fetch/retrieve array Firestore and display on flutter using Getx

I have a restaurant on my collection field, this restaurant has a single offer for example '15% Discount' I have already displayed this part on my flutter app.

Now let's say I have another restaurant who has multiple offer {'0': 'DISCOUNT 5%', '1': 'DISCOUNT 10%'} how would I go to display it on my app, I tried the following but it didn't work

Here is my collection offer field

Here is the code :

class OfferModel {
String id;
List offer;

OfferModel({
this.id,
this.offer,
});

factory OfferModel.fromJson(Map<String, dynamic> json, elementId) =>
  OfferModel(
    id: elementId,
    offer: json ['offer'],
);

Map<String, dynamic> toJson() => {
"offer": offer,
};

class OfferDetail extends StatelessWidget {
final OfferModel currentOffer;
OfferDetail(this.currentOffer);

final controller = Get.put(OfferDetailController());

@override
Widget build(BuildContext context) {
controller.offer = currentOffer;

Widget offerSection = Container(
  child: Text(
    currentOffer.offer,
 );
 return Scaffold(
  body: Stack(
    children: [
      Column(
        children: [
          Expanded(
            child: ListView(
              children: [
                offerSection,
                Padding(
                  padding:
                      EdgeInsets.symmetric(vertical: 15, horizontal: 15),
                  child: Align(
                    child: ButtonFayda(
                      title: 'Get offer',
                      onPressed: () {
                        controller.offerId = currentOffer.id;
                        controller.claimOffer();
                      },
                    ),
                    alignment: Alignment.bottomCenter,
                  ),
                ),
              ],
            ),
          ),
        ],
      )
    ],
   ),
 );
}
}

class OfferDetailController extends GetxController {
var offer = OfferModel();
var offerId;

RxList<OfferModel> offerList = <OfferModel>[].obs;

var isLoading = true.obs;

//rest of the code 

}

Upvotes: 2

Views: 1110

Answers (1)

Dev Anand
Dev Anand

Reputation: 354

I could not understand your code but I could understand your question as below.

You have a object like this

Object{
field1 String,
field2 List<String>
}

In you Firestore you have the data for the respective object. Now you would like to know how to fetch the field2 array.

So this can be achieved using List.castFrom(data['field2']).

For example

QuerySnapshot<Map<String, dynamic>> data = await FirebaseFirestore.instance.collection('object').get();
    List<Object> objList = data.docs.map<Object>((data) =>
     new Shop(
             field1: data['field1'],
             field2: List.castFrom(data['field2'])
    )
    ).toList();

Upvotes: 1

Related Questions