In flutter How to save a list to firebase

Viewed 2357

I have a list in flutter which has offset points.

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

I am trying to save the list to firebase .

  floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.save),
        onPressed: ()=>Firestore.instance.collection('points').add({"point":_points.toString()}),

It is saving to firebase as a string Firebase collection

When i try to save as a list

floatingActionButton: new FloatingActionButton(
          child: new Icon(Icons.save),
        onPressed: ()=>Firestore.instance.collection('points').add({"point":_points.toList()}),

It gives the following error

Invalid argument: Instance of 'Offset'

I need to save it an array instead of a string.How can i get that done

3 Answers

got the answer going through the link provided by @Aldy Yuan

List<String> points1=[];
  List<String> toList1() {

    _points.forEach((item) {
      points1.add(item.toString());
    });

    return points1.toList();
  }

And then i add toList1 in firestore

onPressed: ()=>Firestore.instance.collection('points').add({"point":toList1()}),

Its because you can't save a list of Objects as a field of a document ( unless each list item as a document ) you can mostly add a list of primitive data types as a field of a doc (List<String>, List<int> ... ) , Offset is an object which is not a valid argument since it's not a primitive and that's why it is throwing your error.

In a single line:

'points': _points.map((e) => e.toJson()).toList()

Notice that you need to implement .toJson on your class.

Related