我在一门课程中学习后构建了一个图像选择器。我在调试控制台或构建中没有收到任何错误。我正在尝试单击它,但它不起作用。我在同一个应用程序中以类似的方式制作了另一个图像选择器,但并没有给出任何错误
我的添加图像屏幕:
class _AddImageState extends State<AddImage> {
bool uploading = false;
double val = 0;
CollectionReference? imgRef;
firebase_storage.Reference? ref;
List<File> _image = [];
final picker = ImagePicker();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Add Image'),
actions: [
ElevatedButton(
onPressed: () {
setState(() {
uploading = true;
});
uploadFile().whenComplete(() => Navigator.of(context).pop());
},
child: Text(
'Upload',
style: TextStyle(color: Colors.red),
),
)
],
),
body: Stack(children: [
GridView.builder(
itemCount: _image.length + 1,
gridDelegate:
SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 1),
itemBuilder: (ctx, i) {
return i == 0
? Center(
child: IconButton(
onPressed: () {
!uploading ? chooseImage() : null;
},
icon: Icon(Icons.add)),
)
: Container(
margin: EdgeInsets.all(3),
decoration: BoxDecoration(
image:
DecorationImage(image: FileImage(_image[i - 1]))),
);
}),
uploading
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Container(
child: Text('uploading...',
style: TextStyle(fontSize: 20))),
CircularProgressIndicator.adaptive(
value: val,
valueColor: AlwaysStoppedAnimation<Color>(Colors.green),
)
],
),
)
: Container()
]),
);
}
选择图像功能:
chooseImage() async {
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
setState(() {
_image.add(File(pickedFile!.path));
});
if (pickedFile!.path == null) retrieveLostData();
}
我试过按下:选择图像;但它仍然不起作用
试着像这样轻微地改变你的图像选择器功能-
chooseImage() async {
ImagePicker picker= ImagePicker();
pickedFile = await picker.pickImage(source: ImageSource.gallery);
setState(() {
_image.add(File(pickedFile!.path));
});
if (pickedFile!.path == null) retrieveLostData();
}
为什么file
是最终变量?请确保此函数位于_addImageState或setState((函数内部。如果这些都不起作用,那显然是的权限问题
编辑-
如果你肯定不想在你的__addImageState((中这样做-尝试这样做-
Future<Uint8List> chooseImage(ImageSource source) async {
ImagePicker picker = ImagePicker();
file? file = await picker.pickImage(source: source);
return file;
}
在你称之为的地方
file= await chooseImage();
if (pickedFile!=null){
setState((){
_image.add(File(pickedFile!.path));
});
}