How to instantiate bloc in didChangeDependencies correctly?

Issue

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 happens didChangeDependencies is run again, settings the units back to their default. This prevents me from using any conversions besides the default ones because didChangeDependencies 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

Solution

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

Answered By – Jordan Davies

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.