简体   繁体   中英

Cannot update UI outside of widget using flutter Bloc pattern

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM