flutter firebase get array from Firestore and assign it to a list

Viewed 11901

I have a collection in Firestore. It has a field array i am trying to get the array from Firestore and assign it to a list in flutter. My collection is as below

enter image description here

My code for getting data from Firestore

List<Offset> pointlist = <Offset>[];

 getdata() async{
  await Firestore.instance.collection("points").document('biZV7cepFJA8T6FTcF08').get().then((value){
setState(() {

List<Offset> pointlist = List.from(value.data['point']);

});
   });
  }

  @override
  void initState() {
    super.initState();
    getdata();
  }

i get this error type 'String' is not a subtype of type 'Offset'

2 Answers

The thing which you are doing wrong is this:

// You have initialised your List as a Offset Object Type
List<Offset> pointList;

Secondly, the data you are assigning is a String, if you closely take a look at that firebase.

"Offset(x,y)"

Finally, trying to assign the String value to a List of type Offset class/object

If you want to make the thing works, then either make the List of type String and then add it to the List

List<String> pointlist = List.from(value.data['point']); 

Or first Add the data to the Offset Object like this, and then pass it to the List

List<Offset> pointList = <Offset>[];

getdata() async{
  await Firestore.instance.collection("points").document('biZV7cepFJA8T6FTcF08').get().then((value){
setState(() {
      // first add the data to the Offset object
      List.from(value.data['point']).forEach((element){
          Offset data = new Offset(element);

          //then add the data to the List<Offset>, now we have a type Offset
          pointList.add(data);
      });

      });
   });
  }

SUMMARY

Always look for the data type you are giving to the List, if you are trying to add the data which is not a type T of List<T>, you will always get this error of type mismatch. Hope this will give you some clarity and some basic idea about programming. Keep learning :)

you have to declare list and all list item will be store in declared list so you can access it.

 List<dynamic> alldata =[];

    Future<QuerySnapshot?> getData() async {
        dataofItem = FirebaseFirestore.instance
            .collection('$data')
            .get()
            .then((QuerySnapshot? querySnapshot) {
          querySnapshot!.docs.forEach((doc) {
            allData = doc["item_text_"];
            print("allData = $allData");
            //  print("getData = ${doc["item_text_"]}");
          });
        });
        return dataofItem;
      }
Related