Home > front end >  Append an array into Flutter Firestore
Append an array into Flutter Firestore

Time:04-07

I have a List in Flutter, and I want to add the name field of the objects inside as a list into a collection called requests
List selectedAllergies = [];
enter image description here

However, when I do this, I get this error message:
E/flutter ( 4031): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: Invalid argument: Instance of 'Allergies'

List selectedAllergies = [
    Allergies(id: 1, name: "Milk"),
    Allergies(id: 2, name: "Peanuts"),
    Allergies(id: 3, name: "Tree Nuts"),
    Allergies(id: 4, name: "Eggs"),
    Allergies(id: 5, name: "Soy"),
    Allergies(id: 6, name: "Wheat"),
    Allergies(id: 7, name: "Shellfish"),
    Allergies(id: 8, name: "Snake"),
  ];
class Allergies {
  final int id;
  final String name;

  Allergies({
    required this.id,
    required this.name,
  });
}

Is it possible to append only the "name" field of the selectedAllergies list into a document in the collection of requests?

CodePudding user response:

Firestore doesn't allow adding dart objects directly. See here for a list of supported data types in Firetore.

Instead, as you suggested, we can just add the names of the allergies. The following code illustrates how to get a list of the names.

  List allergyNames = selectedAllergies.map((e) => e.name).toList();

Then, you can add allergyNames to your Firestore document instead.

  • Related