在运行时将图像从计算机上传并显示到 FLUTTER WEB APP

Posted

技术标签:

【中文标题】在运行时将图像从计算机上传并显示到 FLUTTER WEB APP【英文标题】:Uploading and displaying an image from Computer in to a FLUTTER WEB APP during runtime 【发布时间】:2021-02-09 00:47:38 【问题描述】:

我正在尝试通过 FLUTTER WEB 应用程序从我的计算机内部文件夹 (macos) 上传图像,并尝试在同一个 FLUTTER WEB 应用程序中显示相同的图像。上传和显示都是在应用程序运行期间完成的。

我收到以下异常。我该如何解决这个问题?

谢谢。

════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
Expected a value of type 'Widget?', but got one of type 'DecorationImage'

main.dart

import 'dart:convert';
import 'dart:html';
import 'dart:typed_data';

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: ImageUploader(),
    );
  


class ImageUploader extends StatefulWidget 
  @override
  _ImageUploaderState createState() => _ImageUploaderState();


class _ImageUploaderState extends State<ImageUploader> 
  Uint8List imagevalue;

  @override
  Widget build(BuildContext context) 
    final width = MediaQuery.of(context).size.width;

    return Scaffold(
      body: Container(
        width: width,
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 18.0),
              child: Text(
                'Mah Links',
                style: TextStyle(
                  fontFamily: 'Karla',
                  fontSize: 20,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ),
            Container(
                child: imagevalue == null
                    ? Text('No Image')
                    : DecorationImage(
                        fit: BoxFit.cover,
                        image: Image.memory(imagevalue).image)),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        heroTag: 'picker',
        elevation: 0,
        backgroundColor: Colors.tealAccent[400],
        hoverElevation: 0,
        label: Row(
          children: <Widget>[
            Icon(Icons.file_upload),
            SizedBox(width: 10),
            Text('Upload Image')
          ],
        ),
        onPressed: () => uploadImage(),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  

  uploadImage() 
    // HTML input element
    InputElement uploadInput = FileUploadInputElement();
    uploadInput.click();

    uploadInput.onChange.listen(
      (changeEvent) 
        final file = uploadInput.files.first;
        final reader = FileReader();
        // The FileReader object lets web applications asynchronously read the
        // contents of files (or raw data buffers) stored on the user's computer,
        // using File or Blob objects to specify the file or data to read.
        // Source: https://developer.mozilla.org/en-US/docs/Web/API/FileReader

        reader.readAsDataUrl(file);

        String imgString = reader.result; //.toString();
        Uint8List base64string = Base64Decoder().convert(imgString);

        reader.onLoadEnd.listen(
          (loadEndEvent) async 
            setState(() 
              imagevalue = base64string;
            );
          ,
        );
      ,
    );
  

【问题讨论】:

【参考方案1】:

对于任何寻求在运行时从 Flutter Web 应用程序中从计算机内部目录中选择图像的解决方案的人:

确保将 file_picker 包插入 pubspec.yaml

import 'dart:html';
import 'dart:typed_data';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget 
  @override
  Widget build(BuildContext context) 
    return MaterialApp(
      home: ImageUploader(),
    );
  


class ImageUploader extends StatefulWidget 
  @override
  _ImageUploaderState createState() => _ImageUploaderState();


class _ImageUploaderState extends State<ImageUploader> 
  Uint8List imagevalue;

  @override
  Widget build(BuildContext context) 
    final width = MediaQuery.of(context).size.width;

    return Scaffold(
      body: Container(
        width: width,
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.symmetric(vertical: 18.0),
              child: Text(
                'Mah Links',
                style: TextStyle(
                  fontFamily: 'Karla',
                  fontSize: 20,
                  fontWeight: FontWeight.w800,
                ),
              ),
            ),
            Container(
                child: imagevalue == null
                    ? Text('No Image')
                    : Image.memory(imagevalue))
            // : DecorationImage(
            //     fit: BoxFit.cover,
            //     image: Image.memory(imagevalue).image)),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton.extended(
        heroTag: 'picker',
        elevation: 0,
        backgroundColor: Colors.tealAccent[400],
        hoverElevation: 0,
        label: Row(
          children: <Widget>[
            Icon(Icons.file_upload),
            SizedBox(width: 10),
            Text('Upload Image')
          ],
        ),
        onPressed: () => uploadImage(),
      ),
      floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
    );
  

  uploadImage() async 
    FilePickerResult result = await FilePicker.platform.pickFiles(
        type: FileType.custom,
        allowedExtensions: ['png', 'jpg', 'svg', 'jpeg']);

    if (result != null) 
      PlatformFile file = result.files.first;

      setState(() 
        imagevalue = file.bytes;
      );

     else 
      // User canceled the picker
    
  

【讨论】:

以上是关于在运行时将图像从计算机上传并显示到 FLUTTER WEB APP的主要内容,如果未能解决你的问题,请参考以下文章

如何从存储中选择多个图像并在 Flutter 和 Flutter Web App 中显示? [关闭]

Flutter 压缩相机图像

如何在将照片上传到 Firebase 存储时将日期或时间等用户图像详细信息添加到文件名?

Flutter从相册选择图片并显示出来,上传到服务器

单击时将图像添加到屏幕并允许其可拖动/可旋转

将图像从 Firebase 下载到 Flutter