首页 > 解决方案 > 无法使用颤振 Bloc 模式更新小部件外部的 UI

问题描述

我正在尝试 Bloc。在有状态小部件中调用块函数时,它似乎工作正常,例如:

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

这将调用 _nextStep() 函数并更新 UI。nextStep 函数:

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

我用 StreamBuider 搭建小部件,这很有效。但是,如果我在课堂之外调用 _nextStep(),数据会更新,但 UI 不会。例子:

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

如何在小部件之外更新 UI?

标签: flutterdartblocstream-builder

解决方案


我通过使用提供者状态管理解决了我的问题。我声明了一个 SteppBloc 类并将当前步骤分配给 0。然后使用notifyListeners更新使用它的小部件上的值。

StepBloc 类:

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

然后我用StepperBloc的ChangeNotifierProvider包装主 Widget

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

推荐阅读