Flutter:处理错误SocketException:连接失败(操作系统错误:网络无法访问,errno = 101)

时间:2019-09-05 02:35:42

标签: flutter dart

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

我已经做了:

设置Android权限Internet。

我的推荐人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

  

我使用的是真实设备来运行我的应用程序,所以我有意关闭热点以测试未连接到服务器的应用程序。   No Connection Image

1 个答案:

答案 0 :(得分:0)

  1. 确保您在线,无论移动设备还是仿真器,您都已连接到互联网

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