问题描述
喜欢如何在单独的文件中修复样板代码并在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文件并管理如下所示的不同环境:
.Contains(w.Value.CustomerNumber)
,
也许可以不用静态声明您的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
}
}
},),)