我创建了上传图像到应用程序的功能。所以我创建了共享相同onpressed()未来功能的重复按钮
class _HomePage5State extends State<HomePage5> {
// This is the file that will be used to store the image
File? _image;
File? _image2;
late String pickerType;
// This is the image picker
final _picker = ImagePicker();
// Implementing the image picker
Future _openImagePicker(String pickerType,File? pImage )
async {
XFile? pickedImage ;
switch (pickerType) {
case "gallery":
/// GALLERY IMAGE PICKER
pickedImage = await _picker.pickImage(
source: ImageSource.gallery);
break;
case "camera": // CAMERA CAPTURE CODE
pickedImage = await _picker.pickImage(
source: ImageSource.camera);
break;
}
if (pickedImage != null) {
setState(() {
debugPrint("SELECTED IMAGE PICK $pickedImage");
pImage = File(pickedImage!.path);
});
} else {
print("You have not taken image");
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Padding(
padding: const EdgeInsets.all(35),
child: Column(children: [
Center(
// this button is used to open the image picker
child: ElevatedButton(
onPressed: () {
_settingModalBottomSheet(context, _image);
},
child: const Text('Select An Image'),
),
),
const SizedBox(height: 35),
// The picked image will be displayed here
Container(
alignment: Alignment.center,
width: double.infinity,
height: 300,
color: Colors.grey[300],
child: _image != null
? Image.file(_image!, fit: BoxFit.cover)
: const Text('Please select an image'),
),
Center(
// this button is used to open the image picker
child: ElevatedButton(
onPressed: () {
_settingModalBottomSheet(context , _image2);
},
child: const Text('Select An Image'),
),
),
const SizedBox(height: 35),
// The picked image will be displayed here
Container(
alignment: Alignment.center,
width: double.infinity,
height: 300,
color: Colors.grey[300],
child: _image2!= null
? Image.file(_image2!, fit: BoxFit.cover)
: const Text('Please select an image'),
)
]),
),
));
}
我还为重复变量创建了设置模式,所以我不必为每个变量复制相同的函数
void _settingModalBottomSheet(context , File? _imag) {
showModalBottomSheet(
context: context,
builder: (BuildContext bc) {
return Wrap(
children: <Widget>[
ListTile(
title: const Text('Gallery'),
onTap: () => {
_openImagePicker("gallery", _imag),
Navigator.pop(context),
}),
ListTile(
title: const Text('Camera'),
onTap: () => {
_openImagePicker("camera", _imag),
Navigator.pop(context)
},
),
],
);
});
}
但当我运行该项目,似乎未来的功能没有返回图像文件的值,所以图像容器仍然空/空
2条答案
按热度按时间irlmq6kh1#
var value=await _openImagePicker();
vsikbqxv2#
你得到了null,因为你设置了错误的变量。
_openImagePicker()
作为Future〈File?〉函数。show dialog也是一个Future函数。你可以在对话框中调用
_openImagePicker()
。但是我更喜欢把它们分开。现在使用它: