1

I want to retrieve value from if statement of data not a null. At some point the data will be null so with my code it will return the initialize of string. How I want to retrieve the value from if condition that be null

String stringCheck() {
    var checkStatus;
    if (truckState.reported != null) {
      var devStatus = truckState.reported?.data?.status;
      checkStatus = devStatus;
      return checkStatus;
    }
    return checkStatus;
  }

I tried this somehow checkStatus still return null but I need data that hold inside if condition

2
  • could you remove the return statement from the if -statement and test? Commented Dec 10, 2022 at 19:10
  • Hi thanks for the replied @Georgina, if I remove return and make the function nullable, it will not return any value/data instead will stay null as per variable attribute Commented Dec 11, 2022 at 9:05

1 Answer 1

1

In order to return nullable data, you need to change return data type to nullable String? stringCheck().

You can simply do

String? stringCheck() {
  if (truckState.reported != null) {
    String? devStatus = truckState.reported?.data?.status;
    return devStatus;
  }
}

Or just do

String? stringCheck()=>truckState.reported?.data?.status;

More about null-safety

Sign up to request clarification or add additional context in comments.

5 Comments

This is still possible to get an exception in that example, as the data attribute can be null even if the truckState.reported is not. Also, it's better to use an exclamation mark instead of a question mark after the truckState.reported, as it can not be null in these conditions.
In fact, you might not need a mark at all, as Dart can infer that the truckState.reported can not be null inside of this condition statement.
@DmytroPopov Hi, thank you for the answer. yeah true is it possible to have data attribute to have the return inside the if condition or maybe I need to do something like storing in list or anything
If you want to return the data attribute from a function with a non-nullable return type, you can set a default value to return from the function. For example, it can be done with ?? operator: return truckState.reported?.data?.status ?? 'default'. However, I must have mistyped at my comment - with nullable return type you will never get an exception when returning null, so you can freely use the sample code from the answer above. It would be better if you use the second example from the answer, as it is closer to what Effective Dart offers to use.
Thank you for your answer, I'd found the solution whenever the data is not equal to null I will store the the data fetched into get storage then whenever data is null it will return the storage read.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.