I have a Food object that contains properties like name, id, calories, etc. With a series of screens, the user populates the food object properties.

Once done, the user can press the submit button, that will call the addFood method in the store.

The problem is, after uploading the food to the server, i want to pop the screen or show error message in toast based on the response. I just don't know how to do this.

Following is my code (only the important bits): FoodDetailStore.dart

class FoodDetailStore = _FoodDetailStore with _$FoodDetailStore;

abstract class _FoodDetailStore with Store {
  Repository _repository;

  Food _food;

  @observable
  String msg = '';

  // ... Other Observables and actions

  @action
  addFood(bool toAdd) {
    if (toAdd) {
      _repository.addFood(food).then((docId) {
       if (docId != null) {
         // need to pop the screen
       }
      }).catchError((e) {
         // show error to the user.
         // I tried this, but it didn't work
         msg = 'there was an error with message ${e.toString()}. please try again.';
      });
    }

  // .. other helper methods.
}

FoodDetailScreen.dart (Ignore the bloc references, I am currently refactoring code to mobx)

class FoodDataScreen extends StatefulWidget {
  final String foodId;
  final Serving prevSelectedServing;
  final bool fromNewRecipe;

  FoodDataScreen({@required this.foodId, this.prevSelectedServing, this.fromNewRecipe});

  @override
  _FoodDataScreenState createState() => _FoodDataScreenState(
        this.foodId,
        this.prevSelectedServing,
        this.fromNewRecipe,
      );
}

class _FoodDataScreenState extends State<FoodDataScreen> {
  final String foodId;
  final Serving prevSelectedServing;
  final bool fromNewRecipe;

  FoodDataBloc _foodDataBloc;

  _FoodDataScreenState(
    this.foodId,
    this.prevSelectedServing,
    this.fromNewRecipe,
  );

  FoodDetailStore store;

  @override
  void initState() {
    store = FoodDetailStore();
    store.initReactions();
    store.initializeFood(foodId);
    super.initState();
  }

 @override
 void didChangeDependencies() {
   super.didChangeDependencies();
   // I know this is silly, but this is what i tried. Didn't worked
   Observer(
    builder: (_) {
     _showMsg(store.msg);
    }
   );
 }

  @override
  Widget build(BuildContext context) {
    return Container(
    // ... UI  
    );
  }

  _popScreen() {
    _showMsg('Food Added');
    Majesty.router.pop(context);
  }

  _showMsg(String msg) {
    Fluttertoast.showToast(msg: msg);
  }

  @override
  void dispose() {
    store.dispose();
    super.dispose();
  }
}

0 Answers