flutter - 无法使用颤振 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?
解决方案
我通过使用提供者状态管理解决了我的问题。我声明了一个 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,
),
);
}
}
推荐阅读
- python - @object.method 在 Python 中做了什么?
- javascript - 如何找到我要编辑的联系人的 ID?
- sql - 夜班工作人员与 lenel onguard 的持续时间
- jquery - 如何将 $.ajax 与 then() 一起使用?
- javascript - 如何修复自定义警报功能
- vue.js - WebStorm Vue 未解析的变量或类型
- facebook-android-sdk - Facebook 原生广告未显示,错误“1011 - 显示格式不匹配”
- angular - 从命令行自动将新生成的组件添加到 entryComponents
- reactjs - 我正在尝试从 redux-Form 迁移到 react-Final-Form
- javascript - 更改使用 amcharts 绘制的 3D 条形图标签的字体颜色和标题