How to properly set value of DropdownButton using Bloc in Flutter? How to properly set value of DropdownButton using Bloc in Flutter? dart dart

How to properly set value of DropdownButton using Bloc in Flutter?


I solved it using two stream in the bloc, one for the list of elemtns and the other for the value. So in ther build, you need two chained StreamBuilders and when u got both snapshots with data, you load the build. Like that:

Widget _holdingDropDown() {return StreamBuilder(    stream: bloc.holding,    builder: (BuildContext context, AsyncSnapshot<Holding> snapshot) {      return Container(        child: Center(          child: snapshot.hasData              ? StreamBuilder(                  stream: bloc.obsHoldingList,                  builder: (BuildContext context,                      AsyncSnapshot<List<Holding>> holdingListSnapshot) {                    return holdingListSnapshot.hasData ?                    DropdownButton<Holding>(                      value: snapshot.data,                      items: _listDropDownHoldings,                      onChanged: (Holding h) {                        _changeDropDownItemHolding(h);                      },                    ): CircularProgressIndicator();                  },                )              : CircularProgressIndicator(),        ),      );    });}

I use the circular progress indicator to return if I don't have the snapshot with data. I hope I have been helpful.


That's because you are using a StreamBuilder, so at the first time your snapshot is empty, you have to do a validation :

        return snapshot.hasData ?              InputDecorator(                                        decoration: InputDecoration(                                          icon: const Icon(Icons.color_lens),                                          labelText: 'DropDown',                                        ),                                        child: DropdownButtonHideUnderline(                                          child: DropdownButton<String>(                                            value: snapshot.data,                                            onChanged: (String newValue) => _exampleBloc.dropDownSink.add(newValue),                                            items: snapshotValues.data != null ? snapshotValues.data.map<DropdownMenuItem<String>>((String value) {                                              return DropdownMenuItem<String>(                                                value: value,                                                child: Text(value),                                              );                                            }).toList() : SizedBox(height: 0.0)                                        ),                                      ) : SizedBox(height: 0.0);

Display an empty widget SizedBox(height: 0.0) or a CircleProgressIndicator