how to get a list of files from the directory and pass it to the ListView?

Question

Asked by Вячеслав on May 25, 2018 (source).

I get the list of files from the user's folder. The names of the files I transfer to the ListView.builder. It's work, but I think, this is bad architecture.

A method _getFilesFromDir() call with a high frequency.

How to make the correct list generation, so as not to update the interface without changing the file list?

class CharacteristList extends StatefulWidget {
  @override
  _CharacteristListState createState() => new _CharacteristListState();
}    
class _CharacteristListState extends State<CharacteristList> {
  List<String> filesList = new List<String>();
  List<String> filesL = new List<String>();
  @override    
  void initState() {
    super.initState();
    filesList = [];
  }    
  Future<List<String>> _getFilesFromDir() async{
    filesL = await FilesInDirectory().getFilesFromDir();
    setState(() {
      filesList = filesL;
    });
    return filesList;
  }    
  _getFilesCount(){
    _getFilesFromDir();
    int count = filesList.length;
    return count;
  }    
  @override
  Widget build(BuildContext context) {    
    return new Scaffold(
      appBar: new AppBar(
        title: const Text('Список документов'),
      ),
      body: new Column(
        children: <Widget>[
          new Expanded(
              child: new ListView.builder(
                //TODO не успевает сформировать список файлов
                itemCount: _getFilesCount(),
                itemBuilder: (context, index){
                  return new CharacteristListItem(filesList[index]);
                },
              ),
          ),
        ],
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          Navigator.push(context,
              new MaterialPageRoute(builder: (context)
          => new StartScreen()),
          );},
        child: new Icon(Icons.add),
      ),
    );
  }    
}

Answer

Question answered by Günter Z (source).

Don't call _getFilesCount() in build(). build() can be called very frequently. Call it in initState() and store the result instead of re-reading over and over again.

DART FLUTTER
SHARE: