0

I've spend the day stuck on this so I thought I could ask for a little help: I need to write an array in firestore, from a string in flutter.

Basicaly I have MyString = "a,ab,abc,abcd" in flutter. I need to send that to firestore in a new array, each comma in the string separates the values:

#Array

  • a
  • ab
  • abc
  • abcd

Any idea how I could achieve that ?

Full code:

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}
class _MyFormState extends State {

  final _formKey = GlobalKey();
  final _newPerson = Person();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Profile')),
        body: Container(
            padding:
            const EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
            child: Builder(
                builder: (context) => Form(
                    key: _formKey,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          TextFormField(
                            decoration:
                            InputDecoration(labelText: 'Nom'),
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter your first name';
                              }
                            },
                            onChanged: (val) =>
                                setState(() => _newPerson.firstName = val),
                          ),
                          TextFormField(
                              decoration:
                              InputDecoration(labelText: 'Last name'),
                              validator: (value) {
                                if (value.isEmpty) {
                                  return 'Please enter your last name.';
                                }
                              },
                              onChanged: (val) =>
                                  setState(() => _newPerson.lastName = val)),
                          // Container(
                          //   padding: const EdgeInsets.fromLTRB(0, 50, 0, 20),
                          //   child: Text('Subscribe'),
                          // ),
                         // // SwitchListTile(
                         //      title: const Text('Monthly Newsletter'),
                         //      value: _newPerson.newsletter,
                         //      onChanged: (bool val) =>
                         //          setState(() => _newPerson.newsletter = val)),
                         // // Container(
                         //    padding: const EdgeInsets.fromLTRB(0, 50, 0, 20),
                         //    child: Text('Interests'),
                         //  ),
                         //  CheckboxListTile(
                         //      title: const Text('Cooking'),
                         //      value: _newPerson.passions[Person.PassionCooking],
                         //      onChanged: (val) {
                         //        setState(() =>
                         //        _newPerson.passions[Person.PassionCooking] = val);
                         //      }),
                         //  CheckboxListTile(
                         //      title: const Text('Traveling'),
                         //      value: _newPerson.passions[Person.PassionTraveling],
                         //      onChanged: (val) {
                         //        setState(() => _newPerson
                         //            .passions[Person.PassionTraveling] = val);
                         // //      }),
                         //  CheckboxListTile(
                         //      title: const Text('Hiking'),
                         //      value: _newPerson.passions[Person.PassionHiking],
                         //      onChanged: (val) {
                         //        setState(() =>
                         //        _newPerson.passions[Person.PassionHiking] = val);
                         //      }),
                          Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 16.0, horizontal: 16.0),
                              child: RaisedButton(
                                  onPressed: () {
                                  globals.update("nv_personne_nom", (value) => _newPerson.lastName);
                                  globals.update("nv_personne_prenom", (value) => _newPerson.firstName);
                                  print(_newPerson.lastName);
                                  print(_newPerson.firstName);

                              //construction des keywords
                                  String buildkeywords = "";

                              //calcul longueur du nom
                                  int strlength = _newPerson.lastName.length;
                                  print(strlength);
                                  int i = 0;
                                  while (i <= strlength) {
                                  print(_newPerson.lastName.substring(0, i));
                                  buildkeywords = buildkeywords + "," + _newPerson.lastName.substring(0, i);
                              //globals.update("keywords",(value) => (buildkeywords));
                                  i = i + 1;
                                  };
                              //Making a list from the built keyword
                                 //globals.update("keywords",(value) => (buildkeywords));
                                  List<String> arrayOfKeywords = buildkeywords.split(',');
                                

                                  },

                                  child: Text('check')
                              )
                          ),
                          Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 16.0, horizontal: 16.0),
                              child: RaisedButton(
                                  onPressed: () {
                                    createPerson;
                                  },

                                  child: Text('save')
                              )
                          ),
                        ])))));
  }
  _showDialog(BuildContext context) {
    Scaffold.of(context)
        .showSnackBar(SnackBar(content: Text('Submitting form')
    )
    );
  }


}



  final databaseReference = FirebaseFirestore.instance;

  void createPerson() async {


    /* await databaseReference.collection("Personnes")
      .document("BAX")
      .setData({
    'prenom': (globals["nv_personne_prenom"]),
    'nom': (globals["nv_personne_nom"]),
    'keyword': (globals["keyword"]),

  });*/


    DocumentReference ref = await databaseReference.collection("personnes")
        .add({
      // 'personne': '',
      // 'categorie': '',
      // 'Intervenant': '',
      // 'Intervenant': (globals["utilisateur"]),
      // 'nom': (globals["lieu"]),
      'prenom': (globals["nv_personne_prenom"]),
      'nom': (globals["nv_personne_nom"]),
      //'keywords': arrayOfKeywords,

    });

    print(ref.id);
  }

1 Answer 1

1

First, convert string to List

List<String> arrayString = MyString.split(',');

then write an array to firestore

 await FirebaseFirestore.instance.collection('collection').add({'arrayString':arrayString});

EDIT:

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State {
  final _formKey = GlobalKey();
  final _newPerson = Person();
  // initialize an empty array
  List<String> arrayOfKeywords = [];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(title: Text('Profile')),
        body: Container(
            padding:
                const EdgeInsets.symmetric(vertical: 16.0, horizontal: 16.0),
            child: Builder(
                builder: (context) => Form(
                    key: _formKey,
                    child: Column(
                        crossAxisAlignment: CrossAxisAlignment.stretch,
                        children: [
                          TextFormField(
                            decoration: InputDecoration(labelText: 'Nom'),
                            validator: (value) {
                              if (value.isEmpty) {
                                return 'Please enter your first name';
                              }
                            },
                            onChanged: (val) =>
                                setState(() => _newPerson.firstName = val),
                          ),
                          TextFormField(
                              decoration:
                                  InputDecoration(labelText: 'Last name'),
                              validator: (value) {
                                if (value.isEmpty) {
                                  return 'Please enter your last name.';
                                }
                              },
                              onChanged: (val) =>
                                  setState(() => _newPerson.lastName = val)),
                          // Container(
                          //   padding: const EdgeInsets.fromLTRB(0, 50, 0, 20),
                          //   child: Text('Subscribe'),
                          // ),
                          // // SwitchListTile(
                          //      title: const Text('Monthly Newsletter'),
                          //      value: _newPerson.newsletter,
                          //      onChanged: (bool val) =>
                          //          setState(() => _newPerson.newsletter = val)),
                          // // Container(
                          //    padding: const EdgeInsets.fromLTRB(0, 50, 0, 20),
                          //    child: Text('Interests'),
                          //  ),
                          //  CheckboxListTile(
                          //      title: const Text('Cooking'),
                          //      value: _newPerson.passions[Person.PassionCooking],
                          //      onChanged: (val) {
                          //        setState(() =>
                          //        _newPerson.passions[Person.PassionCooking] = val);
                          //      }),
                          //  CheckboxListTile(
                          //      title: const Text('Traveling'),
                          //      value: _newPerson.passions[Person.PassionTraveling],
                          //      onChanged: (val) {
                          //        setState(() => _newPerson
                          //            .passions[Person.PassionTraveling] = val);
                          // //      }),
                          //  CheckboxListTile(
                          //      title: const Text('Hiking'),
                          //      value: _newPerson.passions[Person.PassionHiking],
                          //      onChanged: (val) {
                          //        setState(() =>
                          //        _newPerson.passions[Person.PassionHiking] = val);
                          //      }),
                          Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 16.0, horizontal: 16.0),
                              child: RaisedButton(
                                  onPressed: () {
                                    globals.update("nv_personne_nom",
                                        (value) => _newPerson.lastName);
                                    globals.update("nv_personne_prenom",
                                        (value) => _newPerson.firstName);
                                    print(_newPerson.lastName);
                                    print(_newPerson.firstName);

                                    //construction des keywords
                                    String buildkeywords = "";

                                    //calcul longueur du nom
                                    int strlength = _newPerson.lastName.length;
                                    print(strlength);
                                    int i = 0;
                                    while (i <= strlength) {
                                      print(
                                          _newPerson.lastName.substring(0, i));
                                      buildkeywords = buildkeywords +
                                          "," +
                                          _newPerson.lastName.substring(0, i);
                                      //globals.update("keywords",(value) => (buildkeywords));
                                      i = i + 1;
                                    }
                                    ;
                                    //Making a list from the built keyword
                                    //globals.update("keywords",(value) => (buildkeywords));
                                    arrayOfKeywords = buildkeywords.split(',');
                                  },
                                  child: Text('check'))),
                          Container(
                              padding: const EdgeInsets.symmetric(
                                  vertical: 16.0, horizontal: 16.0),
                              child: RaisedButton(
                                  onPressed: () {
                                    // passing the array to createPerson
                                    createPerson(arrayOfKeywords);
                                  },
                                  child: Text('save'))),
                        ])))));
  }

  _showDialog(BuildContext context) {
    Scaffold.of(context)
        .showSnackBar(SnackBar(content: Text('Submitting form')));
  }
}

final databaseReference = FirebaseFirestore.instance;

void createPerson(List<String> arrayOfKeywords) async {
  /* await databaseReference.collection("Personnes")
      .document("BAX")
      .setData({
    'prenom': (globals["nv_personne_prenom"]),
    'nom': (globals["nv_personne_nom"]),
    'keyword': (globals["keyword"]),

  });*/

// !----------------------------
  DocumentReference ref = await databaseReference.collection("personnes").add({
    // 'personne': '',
    // 'categorie': '',
    // 'Intervenant': '',
    // 'Intervenant': (globals["utilisateur"]),
    // 'nom': (globals["lieu"]),
    'prenom': (globals["nv_personne_prenom"]),
    'nom': (globals["nv_personne_nom"]),
    'keywords': arrayOfKeywords,
  });

  print(ref.id);
}
Sign up to request clarification or add additional context in comments.

5 Comments

That's a great idea, thanks ! Although I can't test it because I'm having trouble to pass the arraystring variable to the void function I use to write in Firestore. Basically I have my main class MyForm which builds the variables from user entries, and when user clicks on submit, a void createPerson() async function is called. But I'm unable to use the variables from MyForm there. Any idea ? (Sorry... that's a question in a question I know :)
try passing the arrayString via a constructor
I'm trying but I just don't get it, my variable is not recognized when I make the constructor. Would you consider real paid tutoring ? I'd be interested, I really need help :)
Updated my question wit the code: I have a _MyFormState class in which the user can enter first and last name. When tapping the check button, first and lastname are stored in a global variable file. Then a list of keywords is built from the lastname (that was my original question). and stored in the arrayOfKeywords variable. After checking, tapping the Save button will call the createPerson void function. There I get my variables previously stored in global, and I also need to get arrayOfKeywords but I don't know how to do.
My problem is that my void function is taking the empty list from the constructor. Not the updated one.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.