标签:return,String,Text,BuildContext,user,context,5.31 From: https://www.cnblogs.com/kongxiangzeng/p/18246582
//注册功能
Future<void> register(
BuildContext context,
String username,
String password,
String username2,
String phoneNumber,
String email)
async {
try {
Dio dio = Dio();
String checkUrl = "http://192.168.211.14:9090/user/checkUserNameExistence?userName=$username";
Response checkResponse = await dio.get(checkUrl);
if (checkResponse.data) {
// 用户名已存在,提示用户无法注册
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('注册失败'),
content: Text('用户名已存在,请选择其他用户名'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop(); // 关闭对话框
},
child: Text('确定'),
),
],
);
},
);
return;
}
// 用户名不存在,可以进行注册
String registerUrl = "http://192.168.211.14:9090/user";
Map<String, dynamic> data = {
"user_name": username,
"user_password": password,
"user_name2": username2,
"user_phone": phoneNumber,
"user_email": email
};
Response response = await dio.post(registerUrl, data: data);
if (response.statusCode == 200) {
// 注册成功
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('注册成功'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop(); // 关闭对话框
Navigator.of(context).pushReplacement( // 替换当前页面为登录页面
MaterialPageRoute(builder: (context) => LoginPage(key: UniqueKey())),
);
},
child: Text('确定'),
),
],
);
},
);
} else {
// 注册失败
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('注册失败'),
content: Text('错误码: ${response.statusCode}'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('确定'),
),
],
);
},
);
}
} catch (e) {
// 请求过程中出现错误
showDialog(
context: context,
builder: (BuildContext context) {
return AlertDialog(
title: Text('请求错误'),
content: Text('$e'),
actions: <Widget>[
TextButton(
onPressed: () {
Navigator.of(context).pop();
},
child: Text('确定'),
),
],
);
},
);
}
}