简体   繁体   中英

Upload multiple files (images) in Flutter Web

I'd like the user to upload (to local memory) multiple files in one upload file element. I am using Flutter web. Below is my current code. Any ideas?

import 'package:flutter/material.dart';
import 'dart:html' as html;
import 'dart:typed_data';

import 'package:phototags/pages/tags_page.dart';

class HomePage extends StatefulWidget {
  HomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  // Code idea from: https://github.com/rjcalifornia/web_upload/blob/master/lib/widgets/web_upload.dart
  List<Uint8List> _selectedFilesBytes;
  GlobalKey<FormState> _formKey = new GlobalKey<FormState>();
  List<Widget> children = [];

  void startWebFilePicker() async {
    html.InputElement uploadInput = html.FileUploadInputElement();
    uploadInput.multiple = true;
    uploadInput.draggable = true;
    uploadInput.click();

    uploadInput.onChange.listen((e) {
      final files = uploadInput.files;

     // _selectedFilesBytes = [];
      for (var i = 0; i < files.length; i++) {
        final file = files[i];
        final reader = new html.FileReader();
        reader.onLoadEnd.listen((event) {
          _selectedFilesBytes.add(reader.result);
        });
        reader.onError.listen((event) {
          print('there was an error');
        });
        reader.readAsArrayBuffer(file);
      }
      setState(() {
        for (var imageBytes in _selectedFilesBytes) {
            children.add(Image.memory(imageBytes));
          }
      });
    });
  }

The current code shows no errors, but it seems to not load anything into the '_selectedFilesBytes' variable.

It seems that the image's bitmap(s) are stored in the memory owned by the temporary input, which gets flushed by the time your app makes it to the build. I've tried creating a copy of image data, using

Image.memory(Uint8List.fromList(reader.result));

directly in the for() cycle the children variable to the widget level. This worked out.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM