如何从目录中获取文件列表并将其传递给 ListView?

Вяч*_*лав 8 dart flutter

我从用户的文件夹中获取文件列表。我传输到 ListView.builder 的文件的名称。这是工作,但我认为,这是糟糕的架构。

一个方法 _getFilesFromDir() 调用频率很高。

如何进行正确的列表生成,以免在不改变文件列表的情况下更新界面?

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),
      ),
    );
  }    
}
Run Code Online (Sandbox Code Playgroud)

Jay*_*iya 13

  // add dependancy in pubspec.yaml
 path_provider:

 import 'dart:io' as io;
    import 'package:path_provider/path_provider.dart';

    //Declare Globaly
      String directory;
      List file = new List();
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        _listofFiles();
      }

    // Make New Function
    void _listofFiles() async {
        directory = (await getApplicationDocumentsDirectory()).path;
        setState(() {
          file = io.Directory("$directory/resume/").listSync();  //use your folder name insted of resume.
        });
      }

    // Build Part
    @override
      Widget build(BuildContext context) {
        return MaterialApp(
          navigatorKey: navigatorKey,
          title: 'List of Files',
          home: Scaffold(
            appBar: AppBar(
              title: Text("Get List of Files with whole Path"),
            ),
            body: Container(
              child: Column(
                children: <Widget>[
                  // your Content if there
                  Expanded(
                    child: ListView.builder(
                        itemCount: file.length,
                        itemBuilder: (BuildContext context, int index) {
                          return Text(file[index].toString());
                        }),
                  )
                ],
              ),
            ),
          ),
        );
      }
Run Code Online (Sandbox Code Playgroud)

  • 而不是“file[index].toString()”,它应该是“file[index].path”,这样我们就可以得到大多数时候我们想要的确切路径。 (3认同)

Gün*_*uer 5

不要叫_getFilesCount()build()build()可以非常频繁地调用。调用它initState()并存储结果,而不是一遍又一遍地重新读取。