image picker颤振不能被使用



我在新的扑动,我做了一个项目使用这个,我有一个问题,
当我想使用imagepicker它不能使用我有以下一步一步在youtube上,我得到错误在

"文件imageFile;说非空实例字段' imageFile'必须初始化。">

和"Pickedfile。Path表示属性' Path '不能被无条件访问,因为接收方可以是'null'。

显示错误的图片

这是我写的代码

File imageFile;
final picker = ImagePicker();
chooseImage(ImageSource source) async {
final PickedFile = await picker.pickImage(source: source);
setState(() {
imageFile = File(PickedFile.path);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {},
icon: Icon(Icons.exit_to_app),
),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Container(
child: imageFile != null
? Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(
image: DecorationImage(
image: FileImage(imageFile),
)),
)
: Container(
height: 120.0,
width: 120.0,
decoration: BoxDecoration(color: Colors.blue),
)),
Container(
child: Padding(
padding: EdgeInsets.fromLTRB(0, 0, 0, 0),
child: ElevatedButton(
onPressed: () {
chooseImage(ImageSource.gallery)
},
child: Text('Ubah Foto Profil'),
),
),
),

让我知道它是否适合你。

ImagePicker picker = ImagePicker();
var imageFile;
_getFromGallery() async {
var pickedFile = (await picker.pickImage(
source: ImageSource.gallery,
));
if (pickedFile != null) {
setState(() {
imageFile = File(pickedFile.path);
});
}
}
Widget _imageSection() {
return (imageFile == null)
? Container(
width:
MediaQuery.of(context).size.width,
height: 220,
child: Card(
elevation: 3.0,
color: Colors.white,
shadowColor: Colors.grey,
// child: Image.asset(ImageUtil
//     .PUNCH_IMAGE_PLACEHOLDER),
child: Text("No image selected"),
),
)
: Container(
/*decoration: BoxDecoration(
border: Border.all(color: 
ColorUtil.leavePageContainerBorder),
),*/
width:
MediaQuery.of(context).size.width,
height: 220,
child: Column(
children: [
// Text(imageFile),
Image.file(imageFile,
fit: BoxFit.cover,
),
],
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
leading: IconButton(
onPressed: () {},
icon: const Icon(Icons.exit_to_app),
),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment:
MainAxisAlignment.start,
children: <Widget>[
Container(
child: Padding(
padding: const EdgeInsets.fromLTRB(
0, 0, 0, 0),
child: ElevatedButton(
onPressed: () {
_getFromGallery();
print(imageFile);
},
child: Text(
'Ubah Foto Profil'),
),
),
),
_imageSection(),
]),
),
),
);
}

这是因为您初始化文件路径为null给出一些值,然后使用setstate()更改它

最新更新