CodeR_Ax20
CodeR_Ax20

Reputation: 151

The value I want is passed to the function by value rather than reference in Flutter. How to avoid this?

Inside my class I have the following class variables,

  Image? _pickedFrontImage;
  Image? _pickedBackImage;

Then I have the below class method,

  void _setPickedImage(String path, Image? image) => setState(     <------ Pay attention to the image parameter
        () => image = Image.file(
          File(path),
          fit: BoxFit.cover,
        ),
      );

The image parameter in this function will receive either of the two variables I have declared above.
However, upon executing the function, I figured my state to not change. The reason for this is, when I pass either _pickedFrontImage or _pickedBackImage, they are passed to the function by value. (Not by reference).

I want to pass these arguments to the function by reference. Not by value. How to do this?

I also came across this stackoverflow link which mentions how to do it for primitives. But I am not dealing with a primitive here. I am using a variable of type Image? . Can someone please help? Thanks.

Upvotes: 0

Views: 614

Answers (1)

nvoigt
nvoigt

Reputation: 77304

Well, just to get the terminology right, you already have passed this by reference. No copy of the Image object was made.

But you don't want to only change the given object and have the changes take effect, you want to replace the whole object. That would only work, if you passed a reference... by reference.

It might be easier to just return the Image object you want and handle the return value. Let the function do one thing (pick an image) and handle your state at the call site.

Upvotes: 1

Related Questions