Trouble with Dart Futures in Flutter : Failed assertion: line 146: '<optimized out>': is not true Trouble with Dart Futures in Flutter : Failed assertion: line 146: '<optimized out>': is not true dart dart

Trouble with Dart Futures in Flutter : Failed assertion: line 146: '<optimized out>': is not true


If you use .then() clauses don't use await.

.then() and await are two different ways to handle Future's but shouldn't be used for the same Future instance.


Consider using async - await to catch the errors in the 'final step'. This answer https://github.com/flutter/flutter/issues/22734 helped me a lot.

Below is a code snippet I got from a source I can't remember but it helped me understand how to properly work with Futures. I modified it a little bit to test for my exact situation (added main4() and divideFullAsyncNested() functions). I hope it helps.

// SO 29378453import 'dart:async';import 'package:login_app/constants.dart';main() {  // fails  main1();  main2();  main3();  main4();}Future<double> divide(int a, b) {  // this part is still sync  if (b == 0) {    throw new Exception('Division by zero divide non-async');  }  // here starts the async part  return new Future.value(a / b);}Future<double> divideFullAsync(int a, b) {  return new Future(() {    if (b == 0) {      throw new Exception('Division by zero full async');    }    return new Future.value(a / b);    // or just    // return a / b;  });}Future<double> divideFullAsyncNested() {  return divideFullAsync(7, 8).then(    (val) {      return divideFullAsync(5, 0).then(        (val2) {          return Future(() {            if (val2 == 1) {              throw Exception('Innermost: Result not accepted exception.');            }            return val2;          });        },      ).catchError((err) => throw Exception('Inner:    $err'));    },  ).catchError((err) => throw Exception('Outter: $err'));}//Future<double> divideFullAsyncNested() {//  return divideFullAsync(9, 9).then(//    (val) {//      return Future(//        () {//          if (val == 1) {//            throw Exception('Result not accepted exception.');//          }//          return val;//        },//      );//    },//  ).catchError((err) => throw Exception(err.toString()));//}// async error handling doesn't catch sync exceptionsvoid main1() async {  try {//    divide(1, 0).then((result) => print('(1) 1 / 0 = $result')).catchError(//        (error) => print('(1)Error occured during division: $error'));    var result = await divide(1, 0);    print('(1) 1 / 0 = $result');  } catch (ex) {    print('(1.1)Error occured during division: ${ex.toString()}');  }}// async error handling catches async exceptionsvoid main2() {  divideFullAsync(1, 0)      .then((result) => print('(2) 1 / 0 = $result'))      .catchError(          (error) => print('(2) Error occured during division: $error'));}// async/await allows to use try/catch for async exceptionsmain3() async {  try {    await divideFullAsync(1, 0);    print('3');  } catch (error) {    print('(3) Error occured during division: $error');  }}main4() async {//  try {//    await divideFullAsyncNested();//  } on Exception catch (e) {//    print("(4) ${e.toString().replaceAll('Exception:', '').trimLeft().trimRight()}");//  }  try {    divideFullAsyncNested()        .then((v) => print(v))        .catchError((err) => print(Constants.refinedExceptionMessage(err)));  } on Exception catch (e) {    print("(4) ${Constants.refinedExceptionMessage(e)}");  }}