Reputation: 69
I need some help regarding the image picker plugin in flutter. I want to let users select images from wherever he/she wants like a camera, gallery, Google drive/photos, or anywhere else not just only one option.
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
class UserImagePicker extends StatefulWidget {
@override
_UserImagePickerState createState() => _UserImagePickerState();
}
class _UserImagePickerState extends State<UserImagePicker> {
File _pickedImage;
void _pickImage() async {
final pickedImageFile =
await ImagePicker().getImage(source: ImageSource.gallery);
setState(() {
_pickedImage = File(pickedImageFile.path);
});
}
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
CircleAvatar(
radius: 40,
backgroundColor: Colors.grey,
backgroundImage:
_pickedImage != null ? FileImage(_pickedImage) : null,
),
FlatButton.icon(
textColor: Theme.of(context).primaryColor,
onPressed: _pickImage,
icon: Icon(Icons.image),
label: Text('Add Image'),
),
],
);
}
}
Upvotes: 2
Views: 5230
Reputation: 7318
Here's a rework of your _pickedImage
to show an alert dialog so the user can choose the source of its image.
void _pickedImage() {
showDialog<ImageSource>(
context: context,
builder: (context) => AlertDialog(
content: Text('Choose image source'),
actions: [
ElevatedButton(
child: Text('Camera'),
onPressed: () => Navigator.pop(context, ImageSource.camera),
),
ElevatedButton(
child: Text('Gallery'),
onPressed: () => Navigator.pop(context, ImageSource.gallery),
),
],
),
).then((ImageSource? source) async {
if (source == null) return;
final pickedFile = await ImagePicker().pickImage(source: source);
if (pickedFile == null) return;
setState(() => _pickedImage = File(pickedFile.path));
});
}
Upvotes: 6
Reputation: 822
Using getX
class UserImagePickerController extends GetxController {
Rx<File> pickedImage = File('').obs;
Future<void> pickImage({required BuildContext context}) async {
await showDialog<ImageSource>(
context: context,
builder: (context) =>
AlertDialog(content: Text("Choose image source"), actions: [
ElevatedButton(
child: Text("Camera"),
onPressed: () => Navigator.pop(context, ImageSource.camera),
),
ElevatedButton(
child: Text("Gallery"),
onPressed: () => Navigator.pop(context, ImageSource.gallery),
),
]),
).then((ImageSource? source) async {
if (source != null) {
final pickedFile = await ImagePicker().pickImage(source: source);
pickedImage.value = File(pickedFile?.path ?? '');
logger.f(pickedFile);
update();
}
});
}
}
Upvotes: 1