I have a ImageManager class that extends ChangeNotifier.
class ImageManager extends ChangeNotifier {
final List<LocalImage> _images = [];
List<LocalImage> get images => _images;
bool get isEmpty => _images.isEmpty;
void addImage(LocalImage image) {
_images.add(image);
notifyListeners();
}
void clear() {
_images.clear();
notifyListeners();
}
Uint8List? getImageData(String referenceId) {
for (var image in _images) {
if (image.referenceId == referenceId) {
return image.imageData;
}
}
notifyListeners();
return null;
}
}
As you can see I have a list of LocalImage.
Here is how I am using it:
_someFunc() async {
final ImagePicker _picker = ImagePicker();
XFile? xFile = await _picker.pickImage(source: ImageSource.gallery);
Uint8List bytes = await xFile!.readAsBytes();
var referenceId = DateTime.now().millisecondsSinceEpoch.toString();
/**
* Create a new instance of LocalImage
*/
LocalImage newInstance = LocalImage(randomId, bytes);
ImageManager().addImage(newInstance);
widget.item.referenceId = randomId;
}
I am storing the reference id in a separate object. So I am using the referenceId to fetch the Uint8List bytes to build an image:
Widget _buildImage() {
return kIsWeb
? Consumer<ImageManager>(
builder: (context, model, _) {
if (!model.isEmpty) {
print('image manager is not empty');
return Image.memory(
model.getImageData(widget.item.referenceId)!,
...////
);
} else {
print('image manager is empty: ${model.images.length}');
return _buildPicker();
}
},
)
: _buildImageMob();
}
But I am always getting image manager is empty. So why is the list still empty even after I add the LocalImage object to the list?
CodePudding user response:
When you call ImageManager().addImage
, you are making a new instance of ImageManager
, instead, you want to use Provider.of<ImageManager>(context).addImage
and make sure your context can reach your provider.