【问题标题】:Flutter : Why is the exception not caught?Flutter:为什么没有捕获到异常?
【发布时间】:2022-01-06 09:26:36
【问题描述】:

我想在发生错误时显示一个快餐栏。 异常正在运行,但未在 main.dart 中捕获。 你能看出什么问题吗?我是 Flutter 的新手,所以我可能不太好。谢谢。

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()}")));
    }
  }

这是 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');
  }
}

【问题讨论】:

    标签: flutter dart exception error-handling try-catch


    【解决方案1】:

    你需要在_signInWithPhoneNumber中调用awaitpostPhoneInfo函数。否则,将在 async 上下文中引发异常。

    你必须使用runZoned 来捕捉这些。 文档:https://api.flutter.dev/flutter/dart-async/runZoned.html

    【讨论】:

      【解决方案2】:

      ScaffoldMessenger.of(context) 必须在 Scaffold 小部件中调用。检查它来自的上下文。

      【讨论】:

        猜你喜欢
        • 2011-11-28
        • 2012-08-14
        • 2017-06-18
        • 2012-01-01
        • 2011-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-16
        相关资源
        最近更新 更多