android - 无法使用图像选择器颤振
问题描述
我是 Flutter 的新手,我用它做了一个项目,我有一个问题,
当我想使用 imagepicker 时,它无法使用,我在 youtube 上一步一步地进行操作,我收到错误
“文件 imageFile;表示必须初始化不可为空的实例字段‘imageFile’。”
并在“Pickedfile.path 表示不能无条件访问属性‘路径’,因为接收器可以是‘空’。”
这张显示错误的图片
这是我写的代码
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(),
]),
),
),
);
}
推荐阅读
- ios - 将ui标签添加到collectionview上的ui imageview
- reactjs - 实用组件内部的挂钩
- python-3.x - 根据目标值计算列中值的平均值
- c++ - 如何删除输出中数字 1 之前的 PERIOD?
- c++ - Visual Studio 2019 是否有用于 c++ 的表单设计器?
- python - Plotly-Dash 未显示图形元素列表
- reactjs - 具有多个 GraphQL 端点的 Apollo
- jpql - 如何编写一个 JPQL 查询,其中一个多对多关系集合应该包含所有给定的实体?
- .net - epplus closedxml 设置自定义属性
- php - 覆盖状态私有 woocommerce 产品的变体