if I use :
uid: user!.uid,
and try to click the post button in my app this error happened :
Exception has occurred. _TypeError (Null check operator used on a null value)
if I try what they say in debug console
: Error: Property 'uid' cannot be accessed on 'UserModel?' because it is potentially null.
lib/…/controller/post_controller.dart:106
- 'UserModel' is from 'package:studyv/models/user_model.dart' ('lib/models/user_model.dart').
package:studyv/models/user_model.dart:1
Try accessing using ?. instead.
uid: user.uid,
^^^
and write it
uid: user?.uid,
this error happened ?:
The argument type 'String?' can't be assigned to the parameter type 'String'.
I will cry!! what should I do when I try to solve it I end up making more errors in my app if someone knows what to do please help !!!!
2
Answers
I think you need to understand how Dart’s null safety works and for that I recommend you read the docs.
The first error you had was because you were trying to read an ‘uid’ property out of a null UserModel Object.
The second error happens because you’re trying to set ‘uid’ (which is of type ‘String’ – meaning it can’t be null) with UserModel’s ‘uid’ which is of type String? (can be null).
The best thing you can do is to check if ‘user.uid != null’ before making that attribution;
Other option (not ideal) is to do something like this:
This will just make your compilation errors go away, but it won’t solve your problem because apparently your UserModel is getting a null value.
Looks like you don’t understand the
null safety
in Dart, you have to learn about it.When you use
uid: user!.uid,
it gives you the error because theuser
instance is null, maybe you didn’t initialize it well. And when you useuid: user?.uid,
it allows you to affect a null to the propertyuid
. You have two solutions, first is to make sure that you initialized theuser
instance before using it somewhere and use!.
with it no problem, second use?.
with??
like this :uid: user?.uid ?? 'default id here'
. I don’t think you should use the second one because it is a user id. so you must use the first one and make sure that the user instance is initialized before you use it. Provide how you initialize it will help figuring a solution for your problem.to understand more about null safety this video may help.
And don’t cry you just need to get things right that’s it.