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();
}
}
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();
})
],
),
),
);
}
}
It's showing me - The 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.
So as discussed in the comments, any variable underscore prefix means this variable is private. So you have two solutions :
_image
and the variable will be accessible from outside the class._image
value.