Flutter Mobx Observer 不重建

标签 flutter mobx

我已经没有想法了。

我使用 Mobx 进行非常简单的状态管理。

import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:jw_helper/state/globalState.dart';

class Router extends StatelessWidget {
  const Router({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _globalState = GlobalState();
    return Column(
      children: <Widget>[
        Container(
          child: Observer(
            builder: (_) => Text(_globalState?.currentIndex?.toString()),
          ),
        ),
        MaterialButton(
          onPressed: () {
            _globalState.setCurrentIndex(1);
          },
          child: Text("Press me"),
        ),
      ],
    );
  }
}

当我改变这个小部件中的状态时,值会更新。 当我在另一个 Widget 中改变同一个 Observable 时,Observer 不会重建。

只有状态发生变化的同一个Widget中的观察者才会被更新。

我的 Mobx 代码:

import 'package:mobx/mobx.dart';

// Include generated file
part 'globalState.g.dart';

// This is the class used by rest of your codebase
class GlobalState = _GlobalState with _$GlobalState;

// The store-class
abstract class _GlobalState with Store {
  @observable
  int currentIndex = 0;

  @action
  void setCurrentIndex(index) {
    currentIndex = index;
    print(currentIndex);
  }
}

小提示:打印语句总是被触发

也许有人知道如何解决这个问题。 谢谢;)

最佳答案

问题已在 Discord Mobx channel 成员的帮助下解决。

解决方案是将整个应用程序包装在提供者小部件中。

class MyApp extends StatelessWidget {
  @override
    Widget build(BuildContext context) {
------------------------------------------------
    return Provider<GlobalState>(
      create: (context) => GlobalState(),
------------------------------------------------
      child: MaterialApp(
        title: 'Flutter Demo',
        debugShowCheckedModeBanner: false,
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: SplashScreen(),
      ),
    );
  }
}

在使用 Mobx 类的小部件中我做了:

class Router extends StatelessWidget {
  const Router({Key key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final _globalState = Provider.of<GlobalState>(context);
    return Column(
      children: <Widget>[
        Container(.....

希望这可以帮助某人启动和运行 ;)

关于Flutter Mobx Observer 不重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59256627/

相关文章:

flutter - 错误:在Flutter中的此Consumer <CartList>小部件上方找不到正确的Provider <CartList>

ios - 有没有办法忽略对 ios 的最小版本依赖并在运行时检查它?

flutter - 如何使用 yield 返回错误(from catch error)

reactjs - 如何结合RxDB和MobX

javascript - 如何创建具有动态返回值的 jest 模拟实现

javascript - MobX 在 ObservableArray.map(..) 中绑定(bind)事件处理程序时抛出错误

flutter - 在 flutter 中将 Firebase 数据获取为 Listview 构建器

flutter - 如何摆脱在 Flutter 上使用 Theme 的上下文依赖?

reactjs - 由 mobx-react 装饰的 PureComponent 抛出有关 `shouldComponentUpdate` 存在的错误

javascript - ReactJS 组件丢失用户输入的输入值