Flutter - Как сохранить выбранный индекс DropDownMenu в FireStore при отправке формы - PullRequest
1 голос
/ 09 июля 2020

Вот мой код для раскрывающегося списка

 Container(
                                      decoration: BoxDecoration(
                                        color: Colors.lightBlueAccent,
                                        //border: ,
                                        borderRadius: BorderRadius.circular(20),
                                      ),
                                      //color: Colors.white,
                                      margin:
                                          EdgeInsets.only(left: 50, right: 50),
                                      child: StreamBuilder<QuerySnapshot>(
                                          stream: Firestore.instance
                                              .collection("Choose Platform")
                                              .snapshots(),
                                          builder: (context, snapshot) {
                                            if (!snapshot.hasData)
                                              const Text("Loading.....");
                                            else {
                                              List<DropdownMenuItem>
                                                  chooseplatform = [];
                                              for (int i = 0;
                                                  i <
                                                      snapshot.data.documents
                                                          .length;
                                                  i++) {
                                                DocumentSnapshot snap =
                                                    snapshot.data.documents[i];
                                                chooseplatform.add(
                                                  DropdownMenuItem(
                                                    child: Text(
                                                      snap.documentID,
                                                      style: TextStyle(
                                                          color: Colors.black),
                                                    ),
                                                    value: "${snap.documentID}",
                                                  ),
                                                );
                                              }
                                              return Row(
                                                mainAxisAlignment:
                                                    MainAxisAlignment.center,
                                                children: <Widget>[
                                                  DropdownButton(
                                                    items: chooseplatform,
                                                    onChanged:
                                                        (choosingplatform) {
                                                      final snackBar = SnackBar(
                                                        content: Text(
                                                          'Selected Platform is $choosingplatform',
                                                          style: TextStyle(
                                                              color: Color(
                                                                  0xff1ffcb7)),
                                                        ),
                                                      );
                                                      Scaffold.of(context)
                                                          .showSnackBar(
                                                              snackBar);
                                                      setState(() {
                                                        chosenPlatform =
                                                            choosingplatform;
                                                      });
                                                    },
                                                    value: chosenPlatform,
                                                    isExpanded: false,
                                                    hint: new Text(
                                                      "Choose Platform",
                                                      style: TextStyle(
                                                          color: Colors.black),
                                                    ),
                                                  ),
                                                ],
                                              );
                                            }
                                          })),

А это код для кнопки Raised

RaisedButton(
                                      padding:
                                          EdgeInsets.only(left: 10, right: 10),
                                      onPressed: () async {
                                        Firestore.instance.runTransaction(
                                            (Transaction transaction) async {
                                          final CollectionReference reference =
                                              Firestore.instance
                                                  .collection('Tournaments');

                                          await reference
                                              .document('Fifa Tournaments')
                                              .collection('Fifa Tourneys')
                                              .add({
                                            'tourneyname':
                                                tourneynameController.text,
                                            'tourneygame':
                                                tourneydateController.text,
                                          });
                                          tourneynameController.clear();
                                          tourneydateController.clear();
                                        });
                                        Navigator.of(context).pop();
                                      },
                                      child: Text(
                                        'Create Tournament',
                                        style: TextStyle(fontSize: 16),
                                      ),
                                      color: const Color(0xff1ffcb7),
                                      textColor: Colors.white,
                                      shape: RoundedRectangleBorder(
                                        borderRadius:
                                            BorderRadius.circular(18.0),
                                        side: BorderSide(color: Colors.white),
                                      ),
                                    ),

Прямо сейчас я могу сохранять значения только для своих TextFormFields а не раскрывающийся список. Вкратце, то, что я сейчас делаю, - это получение значений из коллекции и их отображение в раскрывающемся меню, но я хочу получить значения, а затем сохранить выбранное значение в другой коллекции под названием «Турниры ФИФА», когда форма представлен. Спасибо!

1 Ответ

0 голосов
/ 09 июля 2020

Решено! Все, что мне нужно было сделать, это сохранить переменную для selectedIndex в моей коллекции firestore.

onPressed: () async {
                                    Firestore.instance.runTransaction(
                                        (Transaction transaction) async {
                                      final CollectionReference reference =
                                          Firestore.instance
                                              .collection('Tournaments');

                                      await reference
                                          .document('Fifa Tournaments')
                                          .collection('Fifa Tourneys')
                                          .add({
                                        'tourneyname':
                                            tourneynameController.text,
                                        'tourneygame':
                                            tourneydateController.text,
                                        'tourneyplatform': chosenPlatform,// this is the one
                                       
                                      });
                                      tourneynameController.clear();
                                      tourneydateController.clear();
                                      chosenPlatform.clear();
                                    });
                                    Navigator.of(context).pop();
                                  },
...