【问题标题】:Cannot update UI outside of widget using flutter Bloc pattern无法使用颤振 Bloc 模式更新小部件外部的 UI
【发布时间】:2021-01-18 17:00:16
【问题描述】:

我正在 Flutter 中尝试 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?

【问题讨论】:

  • 那你有什么建议?

标签: flutter dart bloc stream-builder


【解决方案1】:

我通过使用提供者状态管理解决了我的问题。我声明了一个 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,
      ),
    );
  }
}

【讨论】:

    猜你喜欢
    • 2021-01-19
    • 2022-11-12
    • 2020-10-28
    • 2018-11-12
    • 1970-01-01
    • 2019-04-28
    • 2020-09-07
    • 2019-09-14
    • 2019-07-22
    相关资源
    最近更新 更多