skip to Main Content

I am using MVVM and I try to catch error in my view but It crash in the viewmodel with ‘Unhandled Exception: FormatException: Not implemented’

Main app:

void main() {
  WidgetsFlutterBinding.ensureInitialized();
...
  runApp(
....
}

View

  @override
  void initState() {
    super.initState();
    viewModel = Provider.of<TodoViewModel>(context, listen: false);

    WidgetsBinding.instance.addPostFrameCallback((_) {
      try {
        viewModel.getTodos();
      } on FormatException catch (e) {
        DialogMessage.showErrorMessage(context, e.toString());
      }
    });
  }

ViewModel

  Future<void> getTodos() async {
    _isLoading = true;
    notifyListeners();
    try {
      throw const FormatException('Not implemented');
      //_todos = await todoRepository.getTodos();
    } on FormatException catch (e) {
      throw e; // Crash here and don't send error to view
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

Can someone help me please?

2

Answers


  1. Chosen as BEST ANSWER

    Solved. Need to do async/await on the futur method.

    WidgetsBinding.instance.addPostFrameCallback((_) async {
      try {
        await viewModel.getTodos();
      } on FormatException catch (e) {
        DialogMessage.showErrorMessage(context, e.toString());
      }
    });
    

  2. you are intentionally throwing a FormatException in your getTodos method,

    try this:

     Future<void> getTodos() async {
        _isLoading = true;
        notifyListeners();
        try {
          //_todos = await todoRepository.getTodos();
        } on FormatException catch (e) {
          throw e; // Crash here and don't send error to view
        } finally {
          _isLoading = false;
          notifyListeners();
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search