How to instantiate bloc in didChangeDependencies correctly?
Could you just wrap the initialisation and setDefaultUnits
call in an if?
@override
void didChangeDependencies() {
// TODO: implement didChangeDependencies
print("change dependencies ran");
super.didChangeDependencies();
if (_conversionBloc == null) {
_conversionBloc = ConversionProvider.of(context);
_conversionBloc.setDefaultUnits(widget._category);
}
}
Renzo Olivares
Updated on November 20, 2022Comments
-
Renzo Olivares over 1 year
I am attempting to use bloc architecture in a unit conversion app I created from google's flutter udacity course. My issue is with instantiating my bloc. I followed documentation and instantiated my bloc from context as well as some other properties within the didChangeDependencies method. In
didChangeDependencies
I set the default units for the bloc. This works until I focus on a textinput field causing the widget tree to refresh. When this happensdidChangeDependencies
is run again, settings the units back to their default. This prevents me from using any conversions besides the default ones becausedidChangeDependencies
resets the units every time it is called.I have tried instantiating the bloc in init state, but that is not allowed since it is an inherited widget.
class _ConverterScreenState extends State<ConverterScreen> { ConversionBloc _conversionBloc; @override void didChangeDependencies() { // TODO: implement didChangeDependencies print("change dependencies ran"); super.didChangeDependencies(); _conversionBloc = ConversionProvider.of(context); _conversionBloc.setDefaultUnits(widget._category); } @override Widget build(BuildContext context) { print("converter screen - build widget"); // TODO: implement build _conversionBloc.currentCat.add(widget._category); return Scaffold( body: _buildConverterScreen(MediaQuery.of(context).orientation)); } } class ConversionBloc { void setDefaultUnits(Category category) { print("setting default units for ${category.name}"); _inputUnits = category.units[0]; _outputUnits = category.units[1]; _inputUnitSubject.sink.add(_inputUnits); _outputUnitSubject.add(_outputUnits); } }
I expect to change the input/output units to a desired value, and the value not reset when textinput field is focused on or
didChangeDependencies
is called. Currently I change units to desired value, then change focus to text input field, then units reset to default, but that is wrong, units should stay at selected value and not reset. Full source for my project is here https://github.com/Renzo-Olivares/Units_Flutter . Any feedback is appreciated -
Théo Champion over 4 yearswhere does
context
come from here? -
galki over 4 years@ThéoChampion check out this post