Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter CloudFirestore adding complex types throws Invalid argument: Instance of 'Team'

I have class Match that has a list of other classes of type Team. Upload of new document (Match) to Firestore is only possible if the list is empty. Once there is Team item in the list, attempt to add it to Firestore throws 'Invalid argument: Instance of 'Team''. Team class only contains simple fields, no other classes.

Exception is thrown from StandardMessageCodec.writeValue

Update: I am using cloud_firestore: ^0.8.2, and calling

await firestore.collection('matches').document(match.id).setData(match);

since there is no other method that would allow for upload other than setData (accepting Map), I have tried for match.teams (List):

  1. 'teams' : teams (List)
  2. 'teams' : encode to json completely (String)
  3. 'teams' : encode individual Team items and add to collection (List)

1st option will fail, second will create a single string document member and third will create an array of strings inside member, none of which is what I want - create an array of team objects inside document

like image 334
frno Avatar asked Dec 13 '18 14:12

frno


1 Answers

To Completely solve the above problem, follow the following steps:

Steps:

  1. Use json_serializable plugin (link: https://pub.dev/packages/json_serializable)

  2. At the following class level json_serializable annotation to your Match class (note the options)

    part 'match.g.dart'; //actual file will be automatically generated

    @JsonSerializable(anyMap: true, explicitToJson: true)

  3. Do the same(in 2 above) for your Team class(you can ignore the option: explicitToJson):

    part 'team.g.dart'; //will be automatically generated

    @JsonSerializable(anyMap: true)

  4. in your terminal or console (at the root of your project), run: flutter pub run build_runner build to generate all the necessary: *.g.dart files (i.e. match.g.dart, team.g.dart) for your serialized class files

    [pc-name]:[project_root_dir] [username}$ flutter pub run build_runner build

I really hope this helps solve your problem completely as it did mine.

Reference: https://flutter.dev/docs/development/data-and-backend/json

like image 183
Justin Johnson Avatar answered Sep 22 '22 17:09

Justin Johnson