Flutter : Why is the exception not caught?

354

You need to await the postPhoneInfo function call in _signInWithPhoneNumber. Otherwise, the exception is thrown in an async context.

You would have to use runZoned to catch those. Documentation: https://api.flutter.dev/flutter/dart-async/runZoned.html

Share:
354
Kate Jo
Author by

Kate Jo

Updated on January 02, 2023

Comments

  • Kate Jo
    Kate Jo over 1 year

    I want to show a snackbar when an error occurs. The Exception is working but is not caught in the main.dart. Can you see what is the problem? I am new to Flutter so I may not be good. Thank you.

    main.dart

    Future<void> _signInWithPhoneNumber() async {
        try {
          postPhoneInfo(
              tokenValue,
              _packageInfo.appName,
              _packageInfo.version,
              Theme.of(context).platform.toString().substring(15),
              "phone number");
          print("debug : try");
        } catch (e) {
          print("debug : catch");
          // print(e);
          ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text("${e.toString()}")));
        }
      }
    

    this is postPhoneInfo()

    Future<phoneInfo> postPhoneInfo(String token, String appName, String appVersion,
        String platform, String phone) async {
      var queryParameters = {
        'param1': token,
        'param2': appName,
        'param3': appVersion,
        'param4': platform,
        'param5': phone
      };
      var uri =
          Uri.http('~~', '~~', queryParameters);
      final response = await http.post(uri, headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      });
    
      if (response.statusCode == 200) {
        final parsedJson = jsonDecode(response.body);
    
        if (parsedJson["Res"] == "1") {
          print("user is registered");
          return phoneInfo.fromJson(jsonDecode(response.body));
        } else {
          print("user is not registered");
          throw Exception("user is not registered");
        }
      } else {
        print(response.statusCode);
        throw Exception('not connected');
      }
    }