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

Time:03-22

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: ')),
        ],
      ),

CodePudding user response:

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
    ],
  ),
  • Related