DropdownButton giving red screen

Issue

I have a screen that has 2 dropdownbuttons (agency and agents).

When the agency is selected in the first dropdownbutton, the second dropdownbutton, agent, is enabled and populated. When the second dropdownbutton is enabled and populated I am getting an error as seen below. I’m not sure what is happening here. I am getting a red screen where the agent dropdownbutton should be. The rest of the page is fine and I can enter data. Can anyone help please?
”’

======== 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`

”’

the code for the screen is below:

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,
        ),
      ),
    );
  }
}

Solution

I think this is the problem

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

Try to give it some values.

Answered By – Giorgi

Answer Checked By – Clifford M. (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *