flutter - 如何在颤动中使用挑选的图像作为背景图像?
问题描述
我使用了 file_picker 库,因此用户可以选择他最喜欢的图像,然后将其用作我的应用程序中的背景图像。问题是,我无法正确投射。这是一些代码:
floatingActionButton: FloatingActionButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false);
if (result != null) {
var fileBytes = result.files.first.bytes;
if (fileBytes != null) {
blogimage = Image.memory(fileBytes);
setState(() {});
}
}
},
tooltip: 'Select Image',
child: Icon(Icons.select_all),
),
在上面的代码中,我得到了图像。我正在尝试blogimage
用作我的背景图片。我已经尝试过使用容器但失败了。这是我使用的代码:
Widget build(BuildContext context) {
return Container(
decoration: (blogimage != null)? BoxDecoration(image: DecorationImage(image: blogimage)): null,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(widget.title),
),
.....
得到错误:需要一个“ImageProvider”类型的值,但得到一个“Image”类型的值。
有任何想法吗?谢谢阅读。
解决方案
首先,如果要从所选图像中获取字节,则缺少一个参数
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false, withData: true);
withData: true将为您提供所选图像中的字节。
如果不将其设置为 true,result.files.first.bytes将为空。
其次,为什么要将 blogImage 声明为 Image 类型?
请改用 Uint8List 类型并在您的 DecorationImage 中使用 MemoryImage(blogImage)
class FilePickerTest extends StatefulWidget {
@override
_FilePickerTestState createState() => _FilePickerTestState();
}
class _FilePickerTestState extends State<FilePickerTest> {
Uint8List? blogImage;
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
onPressed: () async {
final result = await FilePicker.platform.pickFiles(type: FileType.any, allowMultiple: false, withData: true);
if (result != null) {
blogImage = result.files.first.bytes;
if (blogImage != null) {
setState(() {});
}
}
},
tooltip: 'Select Image',
child: Icon(Icons.select_all),
),
body: Container(
decoration: (blogImage != null) ? BoxDecoration(image: DecorationImage(image: MemoryImage(blogImage!))) : null,
child: Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
title: Text(widget.title),
),
),
),
);
}
}
推荐阅读
- nativescript - 推送通知功能
- python - 为什么 `print(x[0:10:-1])` 和 `print(x[::-1])` 不一样?
- flutter - 如何在 Flutter FutureBuilder 中引用 Firestore documentID
- jquery - jQuery改变名字类型的大小写
- laravel - 开发 Laravel 包时需要在 require 块中添加什么?
- c++ - 构造函数没有被调用
- amazon-web-services - AWS Javascript SDK 仅安装特定模块而不是整个 SDK
- javascript - 第一次单击时输入状态未绑定 onChange
- gnuplot - Gnuplot:如何显示超过 24 小时?
- javascript - 如何正确使用 createPages API 以编程方式创建页面?