-3

I trying to understand the basics of null-safety in dart

what is the best use for this:

// model
class MyModel {
  String? name;
  MyModel({this.name})
}

// view-controller
MyModel? response;

// do some async operations here, on success response get a value


if(response!.name == null){
}

if(response?.name == null){
}

// what is the best practice? and what should i use in this case?
// ! or ?
Igor
  • 399
  • 4
  • 18
  • If `response` can be null, you don't have a choice. `response!` asserts that `response` is not `null` and will crash your program if that assertion is wrong. – jamesdlin Mar 14 '22 at 17:34
  • i got what i was looking for with a good explanation here https://flutterbyexample.com/lesson/null-aware-operators the syntax is called null-aware operator – Igor Mar 14 '22 at 19:21

1 Answers1

-1

Go through this codelab excersie and you will get with basics of using '?' vs '!'.

For reference I am explaining both a bit:

suppose you want to have a string variable which could be, at any point null or can be used to store null value. For this case you can't use String to initialize your variable, instead you need to do it like this way :- String? str

And now the '!' part which is called 'null assertion operator'. Sometimes flutter sdk thought that maybe any variable you have used might be null at runtime and so it throws you error that the object is nullabe. So for that case if you are sure that, the object could never be null at runtime so you need '!' operator to show flutter that it couldn't never be null.

If you have any confusion then do check that codelab exercise for sure.