Flutter-无需单击即可在屏幕加载中检索MobX @action返回值

问题描述

我有MobX @action,可以成功返回一个值。想知道如何在不单击或点击任何内容的情况下在初始屏幕加载中检索值。

abstract class _ProfileMobx with Store {

  @observable
  User user; 

  @observable
  String name = '';

  @action
  Future getClientName() async {
    SharedPreferences pref = await SharedPreferences.getInstance();

    User user = User.fromJson(json.decode(pref.getString('userPref')));
    name = user.name; //successfully return an username from this action
  }
}

希望我可以获取用户名值并将其自动插入到文本小部件中。

final ProfileMobx profileMobx = ProfileMobx();

class ProfileView extends StatelessWidget {
@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Text(profileMobx.name)
        ],),);
  }
}

谢谢!!!

解决方法

您尝试过@computed吗?

基本上computed值是可以从现有状态或其他可观察/计算的值中得出(计算)的值。

我不是100%知道Dart,但是在Javascript / Typescript中,它看起来像这样:

class Profile {
    @observable
    user :User

    @computed get name() {
        return this.user ? this.user.name : '';
    }

    @action
    getUser = async () => {
      // .. your code to get user
      this.user = await getUser();

      // Don't need this line,just set the user,computed will be automatically recalculated
      // name = user.name;
    }
}

此处有关computed的更多信息:https://mobx.js.org/refguide/computed-decorator.html 或者在这里,如果您使用Dart,我想:https://pub.dev/packages/mobx#computed-observables