0

在我的项目中,我定义了一个函数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)
      ],
    );
  }
}



4

1 回答 1

0

您需要将ButtonChange小部件转换为 StatefulWidget 并将uploadPdf()函数移动到状态类中并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');
    });
  });
  
}
于 2021-01-12T01:39:18.347 回答