Flutter Post请求中‘Unhandled Exception: Null check operator used on a null value’异常的解决方法
Hey there! Let's fix that frustrating null check error you're hitting with your Flutter POST request. I've spotted a couple of key issues in your code that are causing this problem—let's break them down and fix them step by step:
1. Your submitData function isn't returning the parsed DataModel
Right now, when your request succeeds (status code 201), you call dataModelFromJSON(responseString) but you don't actually return the parsed object from the function. That means even on success, submitData returns null, and when you use data! in your button press handler, you're forcing a null value to be non-null—hence the exception.
Fixed submitData function:
Future<DataModel?> submitData(String name, String job) async { var response = await http.post( Uri.https('reqres.in', 'api/users'), body: {"name": name, "job": job}, ); var data = response.body; print(data); if (response.statusCode == 201) { String responseString = response.body; // Return the parsed DataModel instead of discarding it return dataModelFromJSON(responseString); } else { return null; } }
2. Don't force-unwrap potentially null data
Even with the fix above, there's still a chance submitData returns null (like if there's a network error or the API returns an unexpected status). Using data! will crash your app if that happens. Instead, check if data is not null before updating your state.
Updated button press handler:
onPressed: () async { String name = nameController.text; String job = jobController.text; DataModel? data = await submitData(name, job); if (data != null) { setState(() { _dataModel = data; }); // Optional: Show success feedback to the user ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("Data submitted successfully!")), ); } else { // Handle failure case ScaffoldMessenger.of(context).showSnackBar( const SnackBar(content: Text("Failed to submit data. Please try again.")), ); } },
3. Add null safety to your DataModel's fromJson method
While the ReqRes API reliably returns id and createdAt, it's good practice to handle potential null values to avoid future crashes. Use the null-coalescing operator (??) to provide default values:
Updated DataModel fromJson:
factory DataModel.fromJson(Map<String, dynamic> json) => DataModel( name: json['name'] ?? "", job: json['job'] ?? "", id: json['id'] ?? "", createdAt: json['createdAt'] ?? "", );
Bonus: Clean up your toJson method
Your current toJson includes id and createdAt, but these are generated by the API—you don't need to send them in your POST request. Let's simplify it:
Map<String, dynamic> toJson() => {"name": name, "job": job};
Once you apply these fixes, your app should no longer throw that null check exception. Test it out by entering a name and job, then hitting submit—you should see the success snackbar and your _dataModel will be properly populated!
内容的提问来源于stack exchange,提问作者Kavishka

