【问题标题】:Flutter : Handling Error SocketException: Connection failed (OS Error: Network is unreachable, errno = 101)Flutter:处理错误 SocketException:连接失败(操作系统错误:网络无法访问,errno = 101)
【发布时间】:2020-01-07 21:33:41
【问题描述】:

我在处理错误SocketException: Connection failed (OS Error: Network is unreachable, errno = 101) address = 192.168.43.159, port = 80 时遇到问题。

我已经做了什么:

设置安卓权限上网。

我的参考Making Network http error SocketException: Failed host lookup

<uses-permission android:name="android.permission.INTERNET"/>

使用try catch 制作函数来处理此错误

是API函数

Future loginMahasiswa(body) async {
    try {
      var apiRespon = await http.post('$baseURL/mahasiswa/login',
          body: body, headers: CrudComponent.headers);
      int statusCode = apiRespon.statusCode;
      if (statusCode == 200) {
        final apiResponJson = json.decode(apiRespon.body);
        print('Success Load Data Json ($apiResponJson)');
        return apiResponJson;
      } else {
        final apiResponJson = json.decode(apiRespon.body);
        print('fail Load Data Json $apiResponJson');
        return apiResponJson;
      }
    } catch (e) {
      print(e);
      return null;
    }
  }

这是按钮功能

  void _loginMahasiswa() async {
    SharedPreferences preferences = await SharedPreferences.getInstance();
    try {
      final body = {"email": _txtEmail.text, "password": _txtPassword.text};
      var loginMahasiswa = await api.loginMahasiswa(body);
      String message = loginMahasiswa['message'];
      var dataUser = loginMahasiswa['data'];
      // String idUser = dataUser[0]['id_user'] ?? "null";
      if (loginMahasiswa['status'] == true) {
        setState(() {
          preferences.setString('token', dataUser[0]['username']);
          Navigator.of(context).pushAndRemoveUntil(
              PageTransition(
                  type: PageTransitionType.rightToLeftWithFade,
                  child: HomePage()),
              (Route<dynamic> route) => false);
        });
      } else {
        print(message);
        _showSnackBar(context, message, Colors.red);
      }
    } on SocketException catch (_) {
      //throw ("No connection Internet");
       _showSnackBar(context, 'no connection', Colors.orange);
    }
  }

但是如果我点击按钮,我的Snackbar 不会显示错误no connection

我正在使用真实设备运行我的应用程序,我特意关闭了热点以测试我的应用程序未连接到服务器。

【问题讨论】:

  • 可以通过cmd或者终端ping吗?
  • @MyName我应该 ping 什么?
  • ping ip地址
  • 从我看到的NoSuchMethodError 异常你没有处理
  • @SwiftingDuster 对不起?所以我不处理SocketException

标签: flutter dart


【解决方案1】:
  1. 确保您在线,无论是移动设备还是模拟器,您都已连接到互联网

2。 确保您已在应用的 android/app/src/main/AndroidManifest.xml 中授予互联网权限

【讨论】:

    猜你喜欢
    • 2019-08-19
    • 2020-09-03
    • 2021-04-18
    • 2018-10-26
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2020-06-07
    • 2013-12-29
    相关资源
    最近更新 更多