Search code examples
flutterflutter-state

How can I update the ListView after getting a certain data?


I have faced this issue,

  • I read files using this _openFile function. After the reading, I want to update the ListView using that extracted data. But I couldn't find a way to reset the state of the ListView after the execution of _openFile.

Any help?

class ListTest extends StatefulWidget {
      @override
      _ListTestState createState() => _ListTestState();
    }

class _ListTestState extends State<ListTest> {

  List<XFile> _files = [];

  Future <List<XFile>> _openFile(BuildContext context) async {
    final XTypeGroup pngTypeGroup = XTypeGroup(
      label: 'PNGs',
      extensions: ['png'],
    );
    _files = await openFiles(acceptedTypeGroups: [
      pngTypeGroup,
    ]);
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        RaisedButton(
          color: Colors.blue,
          textColor: Colors.white,
          child: Text('Press to open images (png)'),
          onPressed: () {
              _openFile(context);
            );
          }
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _files.length,
            itemBuilder: (context, index) {
              return Text(_files[index].path);
            },
          ),
        ),
      ],
    );
  }
}

Solution

  • You need to call setState in order to rebuild the widget. I recommend you to read this.

    You can try something like:

       var _newFiles = await openFiles(acceptedTypeGroups: [
        pngTypeGroup,
      ]);
      setState(() {
        _files = _newFiles;
      });