0

Testing for something that might not exist, is spawning risk of a null but what is the option to acknowledge that and assign good results to a non-null variable?

For example [path_provider getExternalStorageDirectory();] might reasonably respond null in the case there is no external storage.

How can a Directory be assigned, if it does exist, with that risk that might null?

Assigning a temporary variable to test for the null, doesn't work.

Error is consistently then

A value of type 'Directory?' can't be assigned to a variable of type 'Directory'.

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • I do not fully understand the question. Are you asking how to check if a variable is null, only proceed if it is non-null, and at that point handle it as a non-nullable type? – eimmer Jan 06 '23 at 14:28
  • Yes, to assign the reply from getExternalStorageDirectory() that is Directory? to a variable that is Directory. – David Brown Jan 06 '23 at 15:20
  • You either make the variable nullable or you make it `late` and initialize it later. However, making it `late` means that you must guarantee that it is initialized before anything accesses it. – jamesdlin Jan 06 '23 at 18:06
  • Depending on your scenario, you can define a default that will be used in case the nullable is indeed null, example: ```stringLength = str?.length ?? 0``` – eimmer Jan 06 '23 at 18:51

2 Answers2

0

getExternalStorageDirectory() return nullable Directory from future, you can make data type as nullable.

Directory? directory =  await getExternalStorageDirectory();

Find more about understanding-null-safety

Md. Yeasin Sheikh
  • 54,221
  • 7
  • 29
  • 56
  • Obviously you can make a variable nullable to accept the return! The question is about how to get rid of the nullable. Forcing a cascade just because of one nullable, mismatching everything else, seems odd. There should be option to purge the null? – David Brown Jan 06 '23 at 16:33
  • I prefer not forcing it as non-nullable, null-safety is safe IMO, you can do `Directory directory = await getExternalStorageDirectory()!;` but when it return null, you will ended up another error. you can check attach link for more – Md. Yeasin Sheikh Jan 06 '23 at 16:38
0

Reading replies then as "nullable forces nullable", which is workable but odd there is not that option to remove the null.

  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jan 09 '23 at 04:51