flutter - Flutter Mobx Observer 没有重建
问题描述
我已经没有想法了。
我正在使用 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 频道成员的帮助下得到解决。
解决方案是将整个应用程序包装在提供程序 Widget 中。
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(.....
希望这可以帮助某人启动和运行;)
推荐阅读
- google-apps-script - 获取和比较非并发字段的更有效方法 Google 表格(Google 应用脚本)
- javascript - 为什么 localeCompare 不能按我的预期工作?
- c++ - 在蝙蝠类代码中,这给了我错误:重载“蝙蝠()”的调用是模棱两可的蝙蝠();
- c++ - 从类中返回一个字符串——奇怪的行为
- r - R,以变量值为条件删除重复行
- android - Unity 和 Oculus Go。在内部存储上读/写
- python - 从python中的JSON字符串中提取某个值
- sql - 将查询从 LINQ (EF) 转换为 SQL 时,不应用 Where 子句
- java - 如何禁用 JavaFX 中的最大化选项?
- scala - Spark Scala 中的动态映射语句