如何解决无法使用浮动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 包装主窗口小部件
@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,),);
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。