mobxjs / mobx.dart

MobX for the Dart language. Hassle-free, reactive state-management for your Dart and Flutter apps.
https://mobx.netlify.app
MIT License
2.39k stars 310 forks source link

How to wait ObservableFuture.status in function? #984

Open Poloten opened 7 months ago

Poloten commented 7 months ago

I need to open Menu after get data. But after I wait getData method, the List is empty, but if I click second time, the data is exist. Help me please. 1) What's the better pattern ? Maybe I do this wrong. 2) Why I need to wrap parent and child widgets in Observed ? (If I wrap only parent, status in child updated only once).

Store:

 @observable
  ObservableMap<String, ObservableFuture<List<UiItem>>> send = ObservableMap.of({});

  @action
  setDefault(String currency) {
    if (send[currency] == null) send[currency] = ObservableFuture.value([]);
  }

  @action
  Future<void> getSendMenu(String currency) async {
    if (send[currency] == null) setDefault(currency);

    send[currency] = ObservableFuture(getSendMenuItems(currency));

    await send[currency];
  }

child widget

 ObservableFuture<List<UiItem>>? menuObject;

  @override
  Widget build(BuildContext context) {
    return Observer(builder: (_) {
      return OutlinedButton(
        onPressed: () => getMenu().then((_) async => {
             // menuObject?.result  - is exist after second click;
              showMenu(context, menuObject?.result)
            }),
        loading: menuObject != null && menuObject?.status == FutureStatus.pending,
        icon: icon ?? icon,
        text: '$text',
      );
    });
  }

parent widget

@override
Widget build(BuildContext context) {
  final store = Provider.of<MenuStore>(context);

 return Expanded(
    flex: 1,
    child: Observer(builder: (_) {
      return PopupMenuFuture(
        getMenu: () => store.getSendMenu(currency),
        icon: Icons.south_east,
        menuObject: store.send[currency],
        text: 'SEND',
      );
    }),
  ),
}

flutter_mobx: ^2.2.0+2