我想根据服务器发送的内容显示 Flutter 中的任何验证错误。
我觉得我用try-catch太多了,它已经在API中了,然后它在视图中,它也在服务中。这个方法正确吗?.
当我按下按钮时,出现以下对话框:
发生错误: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);
}
}
这是我的视图颤振中的代码按钮:
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'),
),
try-catch 应该正确放置在哪里?
请帮助我能够根据验证服务器在 Flutter 中显示任何验证错误
您的 PHP 端的 try-and-catch 似乎围绕
$request->validate(...)
调用,这是正确的。
问题出在你的 JS/TS 方面,你似乎期望
AuthService.register(...)
方法生成一个数组,但事实并非如此,因此出现错误。
如果您发布所述方法的源代码,或者至少是
print(data)
的输出,我可以提供更多帮助,但基本上就是这样。