flutter - 从Flutter的下拉菜单中删除项目会导致错误

标签 flutter dart google-cloud-firestore

我实现了一个DropDown,其中包含可以删除的项目列表。
删除项目后无法正确显示下拉菜单,这会导致错误,但我不知道如何解决。高度重视帮助!
下拉列表:
enter image description here
这些物品是从Firebase查询的文档的集合。
删除该项目会将其从Firebase中删除,但出现以下错误:
enter image description here
这是我的代码:

var selectedStand;

  void deleteStand() {
    DocumentReference ref = Firestore.instance
        .collection('Standnamen')
        .document(selectedStand);
    ref.delete();
  }


          StreamBuilder<QuerySnapshot>(
            stream: Firestore.instance.collection('Standnamen').snapshots(),
            // ignore: missing_return
            builder: (context, snapshot) {
              if (!snapshot.hasData) {
                Text("Loading");
              } else {
                List<DropdownMenuItem> standItems = [];
                for (int i = 0; i < snapshot.data.documents.length; i++) {
                  DocumentSnapshot snap = snapshot.data.documents[i];
                  standItems.add(
                    DropdownMenuItem(
                      child: Text(
                        snap.documentID,
                        style: TextStyle(color: Colors.blue),
                      ),
                      value: "${snap.documentID}",
                    )
                  );
                }
                return Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: <Widget>[
                    DropdownButton(
                      items: standItems,
                      onChanged: (standValue) {
                        setState(() {
                          selectedStand = standValue;
                        });
                      },
                      value: selectedStand,
                      isExpanded: false,
                      hint: new Text(
                        "Choose stand to delete",
                  ),
                      ),
                    )
                  ],
                );
              }
            },
          ),
        ],
      ),
    );
  }
}
详细错误:
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#46c06):
There should be exactly one item with [DropdownButton]'s value: example3. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 827 pos 15: 'items == null || items.isEmpty || value == null ||
              items.where((DropdownMenuItem<T> item) {
                return item.value == value;
              }).length == 1'

The relevant error-causing widget was: 
  StreamBuilder<QuerySnapshot> file:///Users/darjusch/Developer/flutterProjects/sommerobst_app_beta/lib/screens/admin/admin_create_stand_screen.dart:67:13
When the exception was thrown, this was the stack: 
#2      new DropdownButton (package:flutter/src/material/dropdown.dart:827:15)
#3      _AdminCreateStandScreenState.build.<anonymous closure> (package:sommerobst_app_beta/screens/admin/admin_create_stand_screen.dart:92:23)
#4      StreamBuilder.build (package:flutter/src/widgets/async.dart:509:81)
#5      _StreamBuilderBaseState.build (package:flutter/src/widgets/async.dart:127:48)
#6      StatefulElement.build (package:flutter/src/widgets/framework.dart:4619:28)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
W/erobst_app_bet(20965): Reducing the number of considered missed Gc histogram windows from 119 to 100

════════ Exception caught by rendering library ═════════════════════════════════════════════════════
A RenderFlex overflowed by 99569 pixels on the bottom.
编辑:
我尝试了您的建议,听起来很合逻辑,但没有用,但仍然出现相同的错误。
var selectedDoc;
                      DropdownButton(
                        items: standItems,
                        onChanged: (standValue) {
                          setState(() {
                            selectedStand = standValue;
                            selectedDoc = snapshot.data.documents.firstWhere(
                                  (doc) => doc.documentID == selectedStand,
                              orElse: () => null,
                            );
                          });
                        },
value: selectedDoc?.documentID,

最佳答案

删除后,给DropdownButton一个value(selectedStand),但DropdownMenuItem都不包含。因此,首先检查是否存在idselectedStand的文档,否则将value设置为null

// get the document with id as selectedStand. Will be null if it doesn't exist.
var selectedDoc = snapshot.data.documents.firstWhere(
  (doc) => doc.documentID == selectedStand,
  orElse: () => null,
);

DropdownButton(
  // assign selectedDoc's id (same as selectedStand) if exists
  // otherwise null
  value = selectedDoc?.documentID,
  // ...
),
逻辑不应在onChanged中,而应在DropdownButton中的StreamBuilder之外。
selectedDoc = snapshot.data.documents.firstWhere(
  (doc) => doc.documentID == selectedStand,
  orElse: () => null,
);

return Row(
  mainAxisAlignment: MainAxisAlignment.center,
  children: <Widget>[
    DropdownButton(
      items: standItems,
      onChanged: (standValue) {
         setState(() {
         selectedStand = standValue;
        });
      },
      value: selectedDoc?.documentID,
      isExpanded: false,
      hint: new Text(
        "Choose stand to delete"
      ),
   ),
  ],
),
另外,您可以在找到selectedStand = selectedDoc?.documentID之后立即设置selectedDoc,以便selectedStand始终具有有效值。

关于flutter - 从Flutter的下拉菜单中删除项目会导致错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63136250/

相关文章:

dart - Dart 中是否有相当于 jquery 的 "closest"

angular - Angular 2(4.0.0)Dart变压器不起作用-不支持的操作:需要使用 'angular2'变压器

flutter - 为什么我的小部件上的参数传递为空?

android - 如何将void函数传递给重写的Outline Button类,以便作为onPressed属性工作

text - Flutter 的 TextBaseline 枚举中的字母和表意字母有什么区别

node.js - 在 Node.js 中从 Firestore 检索日期

node.js - 如何从 firebase 集合中获取所有文档,其中每个文档都有一些子集合并且在子集合中有一个文档?

我从 Playstore 下载后,Flutter android 应用程序卡在白屏中

flutter - 自定义 Button 在子 Widget 上有默认的大写文本

java - android setText 在 fragment 内延迟