如果服务器无法访问,如何显示错误

bla*_*ird 2 dart flutter

我对颤振还很陌生。我有一个要执行的网络调用。但在此之前,我需要检查设备是否具有互联网连接以及服务器 api 服务器是否可访问。我已设法检查互联网连接是否可用,但无法显示服务器无法访问的情况

这就是我到目前为止所做的:

 login(username, password) async {
  final String url = "http://10.0.2.2:8080/api/auth/signin"; // iOS
  var responseJson;
  try {
    final response= await http.post(
      url,
      headers: <String, String>{
        'Content-Type': 'application/json; charset=UTF-8',
      },
      body: jsonEncode(<String, String>{
        'username': username,
        'password': password,
      }),
    );
    responseJson = _response(response);
  } on SocketException {
    throw FetchDataException('No Internet connection');
  }
  print(responseJson);
  SharedPreferences prefs = await SharedPreferences.getInstance();
  var parse = jsonDecode(responseJson.body);

  await prefs.setString('username', parse["username"]);
  await prefs.setString('message', parse["message"]);
  await prefs.setString('accessToken', parse["accessToken"]);

  return responseJson;
}
  dynamic _response(http.Response response) {
    switch (response.statusCode) {
      case 200:
        var responseJson = json.decode(response.body.toString());
        print(responseJson);
        return responseJson;
      case 400:
        throw BadRequestException(response.body.toString());
      case 401:

      case 403:
        throw UnauthorisedException(response.body.toString());
      case 500:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response
                .statusCode}');
      default:
        throw FetchDataException(
            'Error occured while Communication with Server with StatusCode : ${response
                .statusCode}');
    }
  }
Run Code Online (Sandbox Code Playgroud)

我的登录按钮功能

 RoundedButton(
                    text: "LOGIN",
                    press: () async {
                      if (_formKey.currentState.validate()) {
                        progressDialog.show();
                        await login(
                          username,
                          password,
                        );
                        SharedPreferences prefs =
                            await SharedPreferences.getInstance();
                        String token = prefs.getString("accessToken");
                        print(token);

                        if (token == null) {
                          progressDialog.hide();
                          showAlertsDialog(context);
                        } else {
                          showAlertzDialog(context);
                        }
                      }
                    },
                  )
Run Code Online (Sandbox Code Playgroud)

每当我切换服务器并单击登录时,应用程序都会卡住显示登录的进度条。如何显示没有连接到服务器的警报?

San*_*rya 6

这是您管理 API 调用的方法。

Future<dynamic> requestGET({String url}) async {
try {
  final response = await http.get(Uri.parse(url));
  switch (response.statusCode) {
    case 200:
    case 201:
      final result = jsonDecode(response.body);
      final jsonResponse = {'success': true, 'response': result};
      return jsonResponse;
    case 400:
      final result = jsonDecode(response.body);
      final jsonResponse = {'success': false, 'response': result};
      return jsonResponse;
    case 401:
      final jsonResponse = {
        'success': false,
        'response': ConstantUtil.UNAUTHORIZED
      };
      return jsonResponse;
    case 500:
    case 501:
    case 502:
      final jsonResponse = {
        'success': false,
        'response': ConstantUtil.SOMETHING_WRONG
      };
      return jsonResponse;
    default:
      final jsonResponse = {
        'success': false,
        'response': ConstantUtil.SOMETHING_WRONG
      };
      return jsonResponse;
  }
} on SocketException {
  final jsonResponse = {
    'success': false,
    'response': ConstantUtil.NO_INTERNET
  };
  return jsonResponse;
} on FormatException {
  final jsonResponse = {
    'success': false,
    'response': ConstantUtil.BAD_RESPONSE
  };
  return jsonResponse;
} on HttpException {
  final jsonResponse = {
    'success': false,
    'response': ConstantUtil.SOMETHING_WRONG  //Server not responding
  };
  return jsonResponse;
 }
}
Run Code Online (Sandbox Code Playgroud)

调用此函数并使用响应我在 statefulWidget 的 init 方法中调用它。

    @override
    void initState() {
    // TODO: implement initState
    super.initState();

    final result = await requestGET('google.com');
    if (result['success'] == false) {
      // show the dialog
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text("Error"),
            content: Text(result['response']),
            actions: [
              FlatButton(
                child: Text("OK"),
                onPressed: () {
                  Navigator.pop(context);
                },
              ),
            ],
          );
          ;
        },
      );
    }
  }
Run Code Online (Sandbox Code Playgroud)