DropdownButton 出现红屏

DropdownButton giving red screen

我的屏幕有 2 个下拉按钮(代理商和代理商)。

当在第一个下拉按钮中选择代理时,第二个下拉按钮代理将启用并填充。当启用并填充第二个下拉按钮时,我收到如下所示的错误。我不确定这里发生了什么。我在代理下拉按钮应该出现的地方出现了一个红色屏幕。页面的其余部分很好,我可以输入数据。有人可以帮忙吗? '''

======== Exception caught by widgets library =======================================================
The following assertion was thrown building StreamBuilder<QuerySnapshot>(dirty, state: _StreamBuilderBaseState<QuerySnapshot, AsyncSnapshot<QuerySnapshot>>#22939):
There should be exactly one item with [DropdownButton]'s value: Select Agent. 
Either zero or 2 or more [DropdownMenuItem]s were detected with the same value
'package:flutter/src/material/dropdown.dart':
Failed assertion: line 850 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:///C:/Users/nkane/AndroidStudioProjects/tonnah/lib/screens/transaction_detail_screen.dart:413:25`

'''

屏幕代码如下:

String loggedInUid;
String _trxnStatus;
String _agencyId;

class TransactionDetailScreen extends StatefulWidget {
  static const String id = 'transaction_detail_screen';
  final QueryDocumentSnapshot trxns;

  TransactionDetailScreen([this.trxns]);

  @override
  _TransactionDetailScreenState createState() =>
      _TransactionDetailScreenState();
}

class _TransactionDetailScreenState extends 
State<TransactionDetailScreen> {
  //final _auth = FirebaseAuth.instance;
  //final _firestoreService = FirestoreService();
  final _db = FirebaseFirestore.instance;
   
  bool showSpinner = false;
  String _currentAgency;
  String _currentAgent = "";
  String _currentStatus = "";

  void changedDropDownAgency(String selectedAgency) {
    setState(() {
      _currentAgency = selectedAgency;
    });
    globals.selectedAgency = selectedAgency;
  }

  void changedDropDownAgent(String selectedAgent) {
    setState(() {
      _currentAgent = selectedAgent;
    });
    globals.selectedAgent = selectedAgent;
  }

  @override
  void initState() {
    getTrxn();
    super.initState();

    _dropDownState = getDropDownState();
    _currentState = _dropDownState[0].value;

    // Set the values from Firestore into the Dropdowns
    if (widget.trxns != null) {
      _currentAgency = widget.trxns['agencyId'];
      _currentAgent = widget.trxns['agentId'];
      _currentState = widget.trxns['propertyState'];
      _trxnStatus = widget.trxns['trxnStatus'];
    } else {
      _currentState = _dropDownState[0].value;
      _trxnStatus = "Select Status";
      _currentAgent = "Select Agent";
    }
  }

  @override
  Widget build(BuildContext context) {
    // Get the stream of transactions created in main.dart
    final trxnProvider = Provider.of<TrxnProvider>(context);
    //final agencyProvider = Provider.of<AgencyProvider>(context);

    return Scaffold(
      //resizeToAvoidBottomInset: true,
      appBar: AppBar(
        automaticallyImplyLeading: false,
        title: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Image.asset('assets/images/Appbar_logo.png',
                fit: BoxFit.cover, height: 56),
          ],
        ),
      ),
      backgroundColor: Colors.white,
      resizeToAvoidBottomInset: false,
      body: SafeArea(
        child: SingleChildScrollView(
          reverse: true,
          child: Padding(
            padding: const EdgeInsets.all(20.0),
            child: Column(
              children: <Widget>[
                Text(
                  'Transaction Details',
                  style: TextStyle(
                    fontSize: 30,
                  ),
                ),
                SizedBox(
                  height: 30.0,
                ),
                Text(
                  'Select agency',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Container(
                  child: StreamBuilder(
                      stream: _db.collection('agency').snapshots(),
                      builder: (BuildContext context, AsyncSnapshot snapshot) {
                        if (snapshot.data == null) {
                          return Center(
                            child: CircularProgressIndicator(),
                          );
                        } else {
                          return new DropdownButton<String>(
                            hint: new Text("Select Agency"),
                            value: _currentAgency,
                            onChanged: changedDropDownAgency,
                            items: snapshot.data.docs
                                .map<DropdownMenuItem<String>>((document) {
                              return new DropdownMenuItem<String>(
                                value: document.id,
                                child: new Text(document.data()['name']),
                              );
                            }).toList(),
                          );
                        }
                      }),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Text(
                  'Select agent',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                SizedBox(
                  height: 8.0,
                ),
                Container(
                  /* Populate the Agent dropdown only if
                     there is an agency to associate the agent with.
                   */
                  child: _currentAgency != null && _currentAgency != ""
                      ? StreamBuilder(
                          stream: _db
                              .collection('agents')
                              .where('agencyId', isEqualTo: _currentAgency)
                              .snapshots(),
                          builder:
                              (BuildContext context, AsyncSnapshot snapshot) {
                            if (!snapshot.hasData) {
                              return Center(
                                child: CircularProgressIndicator(),
                              );
                            } else {
                              return new DropdownButton<String>(
                                hint: new Text("Select Agent"),
                                value: _currentAgent,
                                onChanged: changedDropDownAgent,
                                items: snapshot.data.docs
                                    .map<DropdownMenuItem<String>>((document) {
                                  return new DropdownMenuItem<String>(
                                    value: document.id,
                                    child: new Text(
                                        '${document.data()['fName']} ${document.data()['lName']}'),
                                  );
                                }).toList(),
                              );
                            }
                          })
                      : Container(
                          child: Text('No agents yet'),
                        ),
                ),

                RoundedButton(
                  title: 'Save',
                  colour: Colors.blueAccent,
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      trxnProvider.saveTrxn();
                      globals.targetScreen = 0;
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (context) => MainScreen(),
                        ),
                      );
                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      // todo: add better error handling
                      print(e);
                    }
                  },
                ),
                SizedBox(
                  height: 8.0,
                ),
                RoundedButton(
                  title: 'Delete',
                  colour: Colors.red,
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      trxnProvider.deleteTrxn(widget.trxns['trxnId)']);
                      globals.targetScreen = 0;
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (context) => MainScreen(),
                        ),
                      );
                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      // todo: add better error handling
                      print(e);
                    }
                  },
                ),
                RoundedButton(
                  title: 'Cancel',
                  colour: Colors.orange,
                  onPressed: () async {
                    setState(() {
                      showSpinner = true;
                    });
                    try {
                      globals.targetScreen = 0;
                      Navigator.push(
                        context,
                        new MaterialPageRoute(
                          builder: (context) => MainScreen(),
                        ),
                      );
                      setState(() {
                        showSpinner = false;
                      });
                    } catch (e) {
                      // todo: add better error handling
                      print(e);
                    }
                  },
                )
              ],
            ),
          ),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          setState(() {
            showSpinner = true;
          });
          try {
            trxnProvider.saveTrxn();
            globals.targetScreen = 0;
            Navigator.push(
              context,
              new MaterialPageRoute(
                builder: (context) => MainScreen(),
              ),
            );
            setState(() {
              showSpinner = false;
            });
          } catch (e) {
            // todo: add better error handling
            print(e);
          }
        },
        backgroundColor: kPrimaryColor,
        child: Icon(
          Icons.assignment_turned_in_outlined,
          color: Colors.blueAccent,
        ),
      ),
    );
  }
}

我认为这是问题所在

  String _currentAgency;
  String _currentAgent = "";
  String _currentStatus = "";

尝试给它一些值。

去掉初始化。

 String _currentAgency;
 String _currentAgent;
 String _currentStatus;