我想根据服务器发送的内容在Flutter中显示任何验证错误。
1.我觉得我用try-catch太多了,它已经在API里了,然后它在视图里,它也在服务里,这个方法对吗?
1.当我按下按钮时,出现以下对话框:
出现错误:NoSuchMethodError:方法“[]"在null上调用。
接收器:空。
已尝试调用:[](“消息”)
这是我的API代码:
public function register(Request $request)
{
try {
// Validasi data yang diterima dari klien
$request->validate([
'name' => 'required|string|max:255',
'username' => 'required|string|max:255|unique:users',
'email' => 'required|email|unique:users',
'password' => 'required|string|min:6',
'password_confirmation' => 'required|string|same:password',
]);
// if ($validator->fails()) {
// return response()->json(['validationError' => 'Validasi gagal', 'errors' => $validator->errors()], 400);
// }
// Buat instance User
$user = new User();
$user->name = $request->input('name');
$user->username = $request->input('username');
$user->email = $request->input('email');
$user->password = bcrypt($request->input('password'));
$user->save();
// Kirim respons dengan pesan berhasil dan data pengguna yang terdaftar
return response()->json(['message' => 'Registrasi berhasil!', 'data' => $user], 201);
} catch (ValidationException $e) {
// Tangani kesalahan validasi dengan mengirim respons error dengan status 400 (Bad Request)
return response()->json(['message' => 'Validasi gagal', 'errors' => $e->errors()], 400);
} catch (\Exception $e) {
// Tangani kesalahan dengan mengirim respons error
return response()->json(['message' => 'Registrasi gagal', 'error' => $e->getMessage()], 500);
}
}
字符串
这是我未来的服务功能:
Future register(
{required String name,
required String username,
required String email,
required String password,
required String password_confirmation}) async {
final Map jsonData = {
'name': name,
'username': username,
'email': email,
'password': password,
'password_confirmation': password_confirmation,
};
try {
final Map jsonData = {
'name': name,
'username': username,
'email': email,
'password': password,
'password_confirmation': password_confirmation,
};
Response response = await dio.post('$baseUrl/register', data: jsonData);
print(response.data);
if (response.statusCode == 201) {
final Map<String, dynamic> resultData = response.data;
return resultData;
} else if (response.statusCode == 400) {
final Map<String, dynamic> resultData = response.data;
return resultData;
}
} on DioException catch (e) {
print(e);
}
}
型
这是我的View Flutter的代码按钮:
ElevatedButton(
onPressed: () async {
if (key.currentState!.validate()) {
final navigator = Navigator.of(context);
showDialog(
context: context,
barrierDismissible: false,
builder: (context) {
return const Center(
child: CircularProgressIndicator());
},
);
try {
final data = await AuthService().register(
name: nameC.text,
username: usernameC.text,
email: emailC.text,
password: passwordC.text,
password_confirmation: password_confirmationC.text,
);
print(data);
if (data["message"] == "Registrasi berhasil!") {
navigator.pushAndRemoveUntil(
MaterialPageRoute(
builder: (ctx) => const LoginPage(),
),
(route) => false,
);
} else {
throw Error();
}
} catch (e) {
navigator.pop();
if (e is Map<String, dynamic> &&
e.containsKey("validationError")) {
// Pesan kesalahan validasi diterima dari API
showDialog(
context: context,
builder: (ctx) {
final validationErrors = e["errors"];
final errorMessages = validationErrors.values
.expand((value) => value)
.toList();
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
title: Text('Registrasi Gagal'),
content: Column(
crossAxisAlignment: CrossAxisAlignment.start,
mainAxisSize: MainAxisSize.min,
children: errorMessages.map((message) {
return Text(message.toString());
}).toList(),
),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Ok",
style: TextStyle(color: Colors.green),
),
),
],
);
},
);
} else {
// Kesalahan lain yang bukan validasi
showDialog(
context: context,
builder: (ctx) {
return AlertDialog(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(12),
),
title: Text('Registrasi Gagal'),
content: Text('Terjadi kesalahan: $e'),
actions: [
TextButton(
onPressed: () {
Navigator.pop(context);
},
child: Text(
"Ok",
style: TextStyle(color: Colors.green),
),
),
],
);
},
);
}
}
}
},
style: ElevatedButton.styleFrom(
backgroundColor: Colors.green,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
minimumSize: Size(double.infinity, 50.0),
),
child: Text('Register'),
),
型
1.试接球应该正确放置在哪里?
1.请帮助我能够显示基于验证服务器的Flutter中的任何验证错误
1条答案
按热度按时间nwwlzxa71#
您的PHP端的try-and-catch似乎是围绕
$request->validate(...)
调用,这是正确的。问题出在你的JS/TS端,似乎你期望
AuthService.register(...)
方法得到一个数组,但它不是,因此错误。我可以提供更多的帮助,如果你能张贴说方法的源代码,或至少
print(data)
的输出,但基本上就是这样。