【发布时间】:2020-12-07 10:22:20
【问题描述】:
比如如何在单独的文件中修复样板代码并在 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;
}
}
}
【问题讨论】:
-
不清楚是什么问题。基本 url 似乎设置正确
baseUrl: uri,。然后,您可以使用FutureBuilder小部件在将其公开(假设它在不同的文件中)后使用_loginUser,方法是将其重命名为loginUser。 -
基本 url 样板代码需要在单独的页面中,而不是在同一页面中,并且从使用 apis:like 的所有页面传递的该类 uri 和选项变量中
-
Response response = await dio.post('Uri+/login', data: { "email": email, "password": password, "user_type": 2, "status": 1 },选项:选项);@Er1
-
如果对您有用,请接受以下答案。所以,我们可以节省其他人的时间 :) @SanjeeviRaj