Home > Enterprise >  Firebase Dropdown menu shows hint text as dropdown value (Flutter)
Firebase Dropdown menu shows hint text as dropdown value (Flutter)

Time:07-01

My dropdown menu makes use of Firebase to populate the data. Initially the setState callback did not make any changes to the onChanged property. I finally got this to change by modifying the hint text - it works now, but definitely not as it should or as I want it to work.

My code:

StreamBuilder<QuerySnapshot>(
    stream: FirebaseFirestore.instance
    .collection('field_management')
    .orderBy('block_name')
    .snapshots(),
builder: (context, snapshot) {
    if (!snapshot.hasData) {
        return const Center(
            child: CircularProgressIndicator(),
        );
    }
    return DropdownButton(
        items: snapshot.data!.docs.map((DocumentSnapshot document) {
            return DropdownMenuItem(
                value: document['block_name'],
                child: Text(document['block_name']),
            );
            }).toList(),
        onChanged: (newValue) {
            setState(() => blockDropdownValue = newValue.toString());
        },
        hint: Text(blockDropdownValue),
    );
},
),

What am I doing wrong here?

CodePudding user response:

You are assigning the selected value to the hint property. Don't do that. Assign it to the value property of the DropdownButton widget. By doing this, you will be able to display the selected value after the onChanged callback.

For the hint, give it some other text.

StreamBuilder<QuerySnapshot>(
    stream: FirebaseFirestore.instance
    .collection('field_management')
    .orderBy('block_name')
    .snapshots(),
builder: (context, snapshot) {
    if (!snapshot.hasData) {
        return const Center(
            child: CircularProgressIndicator(),
        );
    }
    return DropdownButton(
        items: snapshot.data!.docs.map((DocumentSnapshot document) {
            return DropdownMenuItem(
                value: document['block_name'],
                child: Text(document['block_name']),
            );
            }).toList(),
        onChanged: (newValue) {
            setState(() => blockDropdownValue = newValue.toString());
        },

        // add the below two lines
        value: blockDropdownValue,
        hint: Text('Select a value'),
    );
},
),
  • Related