Flutter Mobx Observer 不会重建

Cor*_*ius 3 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"),
        ),
      ],
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

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

只有状态发生变化的同一个 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

小提示:打印声明总是被触发

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

Cor*_*ius 5

在 Discord Mobx 频道成员的帮助下问题得到了解决。

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

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(),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在使用 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(.....
Run Code Online (Sandbox Code Playgroud)

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