Home > Software design >  Assignment of null to File variable in Flutter
Assignment of null to File variable in Flutter

Time:02-17

How can I assign null to File variable. I got error when assigning null to File variable.

File myImage=null;
(myImage==null)?
 CircleAvatar(
    backgroundImage:AssetImage('assets/user_new.png'),
    backgroundColor: Colors.cyanAccent,
    radius: 70,
    )
    :
 CircleAvatar(
    backgroundImage:FileImage(myImage),
    backgroundColor: Colors.cyanAccent,
    radius: 70,
    )

CodePudding user response:

Sound null safety is available in Dart 2.12 and Flutter 2.

When using variables you declare are non-nullable by default and to make them nullable you have to use ? after datatype.

example:

int? i = null

In your case, it will be

File? myImage=null;

and you can use it like below:

(myImage==null)?
 CircleAvatar(
    backgroundImage:AssetImage('assets/user_new.png'),
    backgroundColor: Colors.cyanAccent,
    radius: 70,
    )
    :
 CircleAvatar(
    backgroundImage:FileImage(myImage!),
    backgroundColor: Colors.cyanAccent,
    radius: 70,
    )

Here when using myImage you will use ! to tell a program that myImage will not be null.

Note: We should avoid using ! wherever possible as it can cause a run time error but in your case, you are already checking for the null using a ternary operator so you can safely use !.

CodePudding user response:

I suppose you have nullsafety enabled. With nullsafety a variable declared without a ? cannot be null. To fix your issue do the following.

File? myImage = null;

CodePudding user response:

In Flutter null safety is a thing.

With it, no variables can be null if they haven't got a ?. Add a question mark to your File declaration, as:

File? myImage = null;

Down in your code, you will need to check if myImage is null (since now it can be) if you want to assign it to the backgroundImage parameter. You have 2 choices for this:

backgroundImage:FileImage(myImage!) //Null check: Exception throw only if null
backgroundImage:FileImage(myImage ?? 'assets/anotherImage.png') //If: use a standard image if null
  • Related