Flutter: Can't get File from ChangeNotifier

Issue

I am trying to learn provider in flutter. But I am facing a problem. I want to get File _image from ChangeNotifier But it’s showing me error.

Here is ChangeNotifierProvider

class ImagePicker extends ChangeNotifier {
  File _image;
  final picker = ImagePicker();

  Future getImage({ImageSource source}) async {
    final pickedFile = await picker.getImage(source: ImageSource.gallery);

    if (pickedFile != null) {
      _image = File(pickedFile.path);
    } else {
      print('No image selected.');
    }
    notifyListeners();
  }
}

enter image description here

and here is HomeScreen where I want to get that _image file.

class HomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Hello"),
      ),
      body: Container(
        child: Column(
          children: [
            Text("Select a image"),
            Image.file(Provider.of<ImagePicker>(context)._image),
            IconButton(
                icon: Icon(Icons.camera),
                onPressed: () {
                  Provider.of<ImagePicker>(context).getImage();
                })
          ],
        ),
      ),
    );
  }
} 

enter image description here

It’s showing meThe getter ‘_image’ isn’t defined for the type ‘ImagePicker’.
Try importing the library that defines ‘_image’, correcting the name to the name of an existing getter, or defining a getter or field named ‘_image’.

Please some help me for fix this error. And explain what’s happening.

Solution

So as discussed in the comments, any variable underscore prefix means this variable is private. So you have two solutions :

  1. Delete underscore from _image and the variable will be accessible from outside the class.
  2. Define getter that return _image value.

Answered By – ikerfah

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.