Flutter调用Laravel API实现用户注册时出现‘Not found’异常的问题排查求助
Alright, let's figure out why you're hitting that "Not found" exception when trying to register users. The error message is actually misleading—your Flutter code throws this for any non-201 response, which could mean a server error, validation failure, or even a routing issue. Let's fix this step by step:
1. Fix the Token Generation Bug in Laravel (Critical!)
Your Laravel controller has a big issue here: after creating the user, you're calling auth()->user()->createToken(), but the user isn't authenticated yet at this point. auth()->user() will return null, triggering a server error (status code 500), which makes your Flutter app hit the else block and throw "Not found".
Replace this line:
$token = auth()->user()->createToken('myAppToken')->plainTextToken;
With:
$token = $user->createToken('myAppToken')->plainTextToken;
This uses the newly created $user instance directly to generate the token, no authentication required here.
2. Improve Flutter's Error Debugging
Right now, your Flutter code treats every non-201 response as a "Not found" error, which hides the real problem. Let's update the error handling to show actual server response details:
} else { // Print debug info to console first print('Status Code: ${response.statusCode}'); print('Server Response: ${response.body}'); // Throw a more specific error throw Exception('Registration failed: ${response.statusCode} - ${response.body}'); }
Next time something goes wrong, you'll see exactly what the server is sending back—like a 422 validation error (duplicate email, missing field) or 404 route not found.
3. Verify Laravel's API Route
Double-check your routes/api.php to make sure the register route exists and points to the correct controller method:
use App\Http\Controllers\UserController; Route::post('/register', [UserController::class, 'register']);
Laravel's API routes automatically use the /api prefix, so your Flutter URL http://10.0.2.2:8000/api/register is correct as long as this route is defined.
4. Check Request Data & Validation Rules
Make sure your Flutter app is sending all three required fields (name, email, password) with non-empty values. If Laravel's validation fails (e.g., duplicate email), it'll return a 422 status code with error details—your updated Flutter error handling will show this clearly.
Quick Security Note
Your Laravel response includes the plain-text password ('password'=>$fields['password']), which is a bad security practice. Remove that from the response array:
return response([ 'name'=>$fields['name'], 'email'=>$fields['email'], 'token'=>$token ], 201);
Follow these steps, and your registration flow should work as expected. If you still run into issues, check the Flutter console for the detailed server response—it'll point you straight to the problem.
内容的提问来源于stack exchange,提问作者josef

