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

标签 flutter 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}');
    }
  }

我的登录按钮功能

 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);
                        }
                      }
                    },
                  )

每当我切换服务器并点击登录时,应用程序就会卡在一个显示登录的进度条上。如何显示没有连接到服务器的警告?

最佳答案

这就是您管理 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;
 }
}

调用这个函数并使用response 我在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);
                },
              ),
            ],
          );
          ;
        },
      );
    }
  }

关于flutter - 如果服务器无法访问,如何显示错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65377295/

相关文章:

flutter - flutter 中的 Stripe 实现

flutter - Dart 中的 yield 和 yield* 之间的差异

firebase - 如何通过索引删除特定数组

flutter - 如何从Flutter中的异步函数安全地调用setState函数?

flutter - 如何使 SingleChildScrollView 在需要时用空白填充全屏高度

flutter - 检查对象是否有空值

dart - 获取Dart Polymer元素资源URL

flutter - Navigator.of(context).pop();使整个屏幕消失,而不是弹出窗口

android - Gradle 构建无法解析所有 Path_provider 依赖项

dart - Flutter - CustomPainter 中自下而上的动画