本文介绍了如何设置基本 URL 以及在 flutter dio 中为 api 调用声明它的位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

喜欢如何在单独的文件中修复样板代码并在 ui 页面中使用它.

我需要在单独的文件中声明这个 uri 变量并在所有页面上访问:

  static var uri = "https://xxx/xxx/web_api/public";
  static BaseOptions options = BaseOptions(
  baseUrl: uri,
  responseType: ResponseType.plain,
  connectTimeout: 30000,
  receiveTimeout: 30000,
  // ignore: missing_return
  validateStatus: (code) {
    if (code >= 200) {
      return true;
    }
  });  static Dio dio = Dio(options);

在 UI 页面中,我必须在这个未来的函数中声明 uri 变量和 BaseOption 变量:

   Future<dynamic> _loginUser(String email, String password) async {
     try {
  Options options = Options(
    headers: {"Content-Type": "application/json"},
  );
  Response response = await dio.post('/login',
      data: {
        "email": email,
        "password": password,
        "user_type": 2,
        "status": 1
      },
      options: options);

  if (response.statusCode == 200 || response.statusCode == 201) {
    var responseJson = json.decode(response.data);
    return responseJson;
  } else if (response.statusCode == 401) {
    throw Exception("Incorrect Email/Password");
  } else
    throw Exception('Authentication Error');
} on DioError catch (exception) {
  if (exception == null ||
      exception.toString().contains('SocketException')) {
    throw Exception("Network Error");
  } else if (exception.type == DioErrorType.RECEIVE_TIMEOUT ||
      exception.type == DioErrorType.CONNECT_TIMEOUT) {
    throw Exception(
        "Could'nt connect, please ensure you have a stable network.");
  } else {
    return null;
  }
}

}

推荐答案

您可以创建 app_config.dart 文件并管理不同的环境,如下所示:

You can create app_config.dart file and manage different environments like below:

const _baseUrl = "baseUrl";

enum Environment { dev, stage, prod }

Map<String, dynamic> _config;

void setEnvironment(Environment env) {
  switch (env) {
    case Environment.dev:
      _config = devConstants;
      break;
    case Environment.stage:
      _config = stageConstants;
      break;
    case Environment.prod:
      _config = prodConstants;
      break;
  }
}

dynamic get apiBaseUrl {
  return _config[_baseUrl];
}

Map<String, dynamic> devConstants = {
  _baseUrl: "https://devapi.xyz.com/",
};


Map<String, dynamic> stageConstants = {
  _baseUrl: "https://api.stage.com/",
};

Map<String, dynamic> prodConstants = {
  _baseUrl: "https://api.production.com/",
};

这篇关于如何设置基本 URL 以及在 flutter dio 中为 api 调用声明它的位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-27 17:25