Cannot update UI outside of widget using flutter Bloc pattern

367 views Asked by At

I am trying out Bloc in flutter. It seems to work fine when calling a block function in a stateful widget for example:

 RaisedButton(
 onPressed: () => _nextStep(),
 child: Text("Next"))

This would call the _nextStep() function and update the UI. The nextStep function:

  _nextStep() async {
_bloc.StepEventSink.add(NextStep());
}

and I scafold the widget with StreamBuider and that works. But if i call _nextStep() outside of the class, the data updates but the UI don't. Example:

class FormWizard extends StatefulWidget {
  @override
 _FormWizardState createState() => _FormWizardState();
  next() {
_FormWizardState()._nextStep();
  }
 }

How can I update the UI outside of the widget?

1

There are 1 answers

0
jr3000 On

I solved my issue by using Provider State management. I declared a SteppBloc class and and assign the current step to 0. Then use notifyListeners to update the value on widgets that uses it.

StepBloc class:

import 'package:flutter/material.dart';

class StepperBloc extends ChangeNotifier {
  int _current = 0;
  int get currentStep => _current;

  set currentStep(int val) {
    _current = val;
    notifyListeners();
  }

  increment() {
    _current++;
    notifyListeners();
  }

  decrement() {
    _current--;
    notifyListeners();
  }
}

Then I wrap the main Widget with ChangeNotifierProvider of StepperBloc

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider<StepperBloc>.value(value: StepperBloc())
      ],
      child: MaterialApp(
        debugShowCheckedModeBanner: false,
        theme: theme(),
        home: loading(),
        //initialRoute: SplashScreen.routeName,
        routes: routes,
      ),
    );
  }
}