0

I have MobX @action which successfully return a value. Wondering how to retrieve the value in initial screen load without click or tap anything.

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
  }
}

I hope I can get the username value and inserted automatically to text widget.

final ProfileMobx profileMobx = ProfileMobx();

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

Thanks !!!

Wannabe
  • 13
  • 4

1 Answers1

1

Have you tried @computed?

Basically computed values are values that can be derived (computed) from the existing state or other observable/computed values.

I am not 100% sure about Dart, but in Javascript/Typescript it would look something like that:

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;
    }
}

More info about computed here: https://mobx.js.org/refguide/computed-decorator.html Or here, if you use Dart, I guess: https://pub.dev/packages/mobx#computed-observables

Danila
  • 15,606
  • 2
  • 35
  • 67