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

Issue

In my project, I have defined a function uploadPdf().
Calling this function at Raised Button to pick a file and it works fine. And it printing the fileName. Now what I want to get that fileName to Text Widget. For that, I defined fileName as a Global variable, and initially assigned value. Calling this variable in the uploadPdf() function, so that when a new value gets it updates the value, but it not changing. It still shows the same value that I assigned initially.
Thanks!


//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)
      ],
    );
  }
}



Solution

You will need to convert the ButtonChange widget to a StatefulWidget and move the uploadPdf() function inside the state class and call setState after you update the filename.

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');
    });
  });
  
}

Answered By – Calvin Gonsalves

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *