【问题标题】:Uploading and displaying an image from Computer in to a FLUTTER WEB APP during runtime在运行时将图像从计算机上传并显示到 FLUTTER WEB APP
【发布时间】: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;
            });
          },
        );
      },
    );
  }
}

【问题讨论】:

    标签: flutter flutter-web


    【解决方案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
        }
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2016-04-03
      • 2018-08-11
      • 1970-01-01
      • 1970-01-01
      • 2021-03-21
      • 2021-08-05
      • 2020-11-28
      • 2021-08-11
      • 2022-07-28
      相关资源
      最近更新 更多