Flutter Mobx观察器未重建

问题描述 投票:0回答:1

我不知道了。

我正在使用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"),
        ),
      ],
    );
  }
}

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

仅更新状态被更改的同一小部件​​中的观察者。

我的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);
  }
}

小注释:总是会打印语句

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

flutter mobx
1个回答
0
投票

问题已在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(),
      ),
    );
  }
}

在使用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(.....

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

© www.soinside.com 2019 - 2024. All rights reserved.