喜欢如何在单独的文件中修复样板代码并在用户界面页面中使用它。
我需要在单独的文件中声明此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;
}
}
}
3条答案
按热度按时间ohtdti5x1#
您可以创建app_config.dart文件并管理不同的环境,如下所示:
l0oc07j22#
也许,您可以将
Dio
对象放在一个类中,也可以将loginUser
函数放在其中,然后使用Provider
获取该对象,以便在需要时调用它。https://pub.dev/packages/provider
https://api.flutter.dev/flutter/widgets/FutureBuilder-class.html
0g0grzrc3#
我在
.env
文件中设置了domain和env值,然后使用dotenv pacckage读取它本地.环境
设备环境
下面的函数根据环境给出url(http或https),也根据环境使用域