如何设置一个基本的URL,在flutter dio中的什么地方声明它来调用API?

bmp9r5qi  于 2023-02-25  发布在  Flutter
关注(0)|答案(3)|浏览(145)

喜欢如何在单独的文件中修复样板代码并在用户界面页面中使用它。
我需要在单独的文件中声明此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;
  }
}

}

ohtdti5x

ohtdti5x1#

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

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/",
};
l0oc07j2

l0oc07j22#

也许,您可以将Dio对象放在一个类中,也可以将loginUser函数放在其中,然后使用Provider获取该对象,以便在需要时调用它。

class Api {
  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;
    }
  }); 
  Dio dio = Dio(options);

  Future<dynamic> loginUser(String email, String password) async {
    try {
      RequestOptions options = RequestOptions(
        headers: {"Content-Type": "application/json"},
      );
    Response response = await dio.post('/login',
        data: {
          "email": email,
          "password": password,
          "user_type": 2,
          "status": 1
        },
        options: options);
    //the rest of your code here
}

https://pub.dev/packages/provider

Provider(
  create: (_) => Api(),
  child: ...
)

https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html

YourWidget(
  child: Consumer<Api>(
    builder: (context, api, child) {
      return FutureBuilder<dynamic>(
      future: api.loginUser('mail@mail.com', 'user_password')
      builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
        if (snapshot.hasData) {
          //show a widget based on snapshot.data
        } else {
          //show another widget
        }
      }
    },
  ),
)
0g0grzrc

0g0grzrc3#

我在.env文件中设置了domain和env值,然后使用dotenv pacckage读取它

本地.环境

env=local
apidomain=localhost:8000

设备环境

env=dev
apidomain=xyz.com

下面的函数根据环境给出url(http或https),也根据环境使用域

import 'package:flutter_dotenv/flutter_dotenv.dart';

Uri getCompleteUrl({required String url}) {
  // if local env then http else https url
  String domain = dotenv.get('apidomain'); // localhost:8000 or xyz.com
  if (dotenv.get('env') == 'local') {
    return Uri.http(domain, url);
  } else {
    return Uri.https(domain, url);
  }
}

相关问题