Flutter: What option is there to assign variable? to variable - null can't be assigned to non-null; path_provider getExternalStorageDirectory();

103 views Asked by At

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'.

2

There are 2 answers

2
Md. Yeasin Sheikh On

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

Directory? directory =  await getExternalStorageDirectory();

Find more about understanding-null-safety

1
David Brown On

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