0

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



Prateek
  • 502
  • 5
  • 16

1 Answers1

2

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');
    });
  });
  
}
Calvin Gonsalves
  • 1,738
  • 11
  • 15
  • Thank its working, but they're a small issue...I need to click on the Button again and have to cancel then it updates the last value. – Prateek Jan 12 '21 at 04:42
  • 1
    @Prateek I updated my answer. I guess the `onChange` is asynchronous so the setState would be executed before the fileName is updated. please move the `setState` in the onChange event and it will update immediately. – Calvin Gonsalves Jan 12 '21 at 05:00
  • 1
    Thank @Calvin, now it updating the file name immediately. – Prateek Jan 12 '21 at 05:05