Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Not able to display the value of a variable defined out of a widget

i’m new to dart and i’m trying to display the file name inside the Text widget!
I first took out the file’s name inside the onPressed function, but later on couldn’t access it in order to display it, can anyone help me out with this issue? thank in advance.

Here is my code:

body: Column(
        children: [
          ElevatedButton(
              onPressed: () async {
                final result = await FilePicker.platform.pickFiles();
                if (result == null) return;

                final file = result.files.first;
                /* print(file.extension);
                print(file.name); */
                final FileName = file.name;

                final newFile = await saveFilePermanently(file);

                print('Old: ${file.path}');
                print('New: ${newFile.path}');
              },
              child: const Text('Name: ')),
        ],
      ),

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to create a variable to store the file name outside your onPressed method and use setState() to update your variable value.

String fileName = '';
...
body: Column(
    children: [
      ElevatedButton(
          onPressed: () async {
            final result = await FilePicker.platform.pickFiles();
            if (result == null) return;

            final file = result.files.first;
            /* print(file.extension);
            print(file.name); */
            final FileName = file.name;

            final newFile = await saveFilePermanently(file);

            print('Old: ${file.path}');
            print('New: ${newFile.path}');
            // add this setState to update your variable value
            setState(() {
               fileName = newFile.path; 
            });
          },
          child: const Text('Name: $fileName')), // show your value here
    ],
  ),
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading