首页 > 解决方案 > 如何在颤动中使用挑选的图像作为背景图像?

问题描述

我使用了 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”类型的值。

有任何想法吗?谢谢阅读。

标签: flutterdartstatefulwidget

解决方案


首先,如果要从所选图像中获取字节,则缺少一个参数

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),
          ),
        ),
      ),
    );
  }
}

推荐阅读