简体   繁体   中英

In flutter How to save a list to firebase

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 集合

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

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.

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()}),

In a single line:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM