Flutter Web中使用dart:HTML库选取文件时,如何获取Flutter中的文件名?

How to get the file name in Flutter when using dart:HTML library to pick file in Flutter Web?

在我的项目中,我定义了一个函数uploadPdf()。 在 Raised Button 调用这个函数来选择一个文件,它工作正常。并打印文件名。现在我想将该文件名获取到文本小部件。为此,我将 fileName 定义为全局变量,并初始赋值。在 uploadPdf() 函数中调用此变量,以便在获取新值时更新值,但不会更改。它仍然显示我最初分配的相同值。 谢谢!


//Flutter Full Code
import 'package:flutter/material.dart';
import 'dart:html';

String fileName = "no item selected";

void uploadPdf() {
  InputElement uploadInput = FileUploadInputElement()..accept = 'pdf/*';
  uploadInput.click();
  uploadInput.onChange.listen((event) {
    final file = uploadInput.files.first;
    fileName = file.name;
    print(fileName);
    final reader = FileReader();
    reader.readAsDataUrl(file);
    reader.onLoadEnd.listen((event) {
      print('done');
    });
  });
}

class ButtonChange extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        RaisedButton(
          onPressed: () => uploadPdf(),
          child: Text("Upload Button"),
        ),
        Text(fileName)
      ],
    );
  }
}



您需要将 ButtonChange 小部件转换为 StatefulWidget,并将 uploadPdf() 函数移动到状态 class 内,并在更新文件名后调用 setState

void uploadPdf() {
  InputElement uploadInput = FileUploadInputElement()..accept = 'pdf/*';
  uploadInput.click();
  uploadInput.onChange.listen((event) {
    final file = uploadInput.files.first;
    setState(() {
       fileName = file.name; 
    });
    fileName = file.name;
    print(fileName);
    final reader = FileReader();
    reader.readAsDataUrl(file);
    reader.onLoadEnd.listen((event) {
      print('done');
    });
  });
  
}