You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Flutter访问Windows指定文件夹并展示其中文件列表

Flutter Windows 访问指定文件夹并展示文件列表

你可以直接使用Dart标准库中的dart:io实现需求,无需依赖复杂第三方包,操作门槛低,具体步骤如下:

实现步骤

  1. 导入dart:io包
    这是Dart自带的IO操作库,无需额外安装依赖,直接导入即可:

    import 'dart:io';
    
  2. 读取指定目录内容
    使用Directory类的异步方法list()获取目录下的文件和子目录,该方法返回Stream<FileSystemEntity>,适合UI场景的异步处理;也可使用listSync()同步读取,但异步方式更友好。

  3. 解析文件/目录信息
    通过FileSystemEntity的属性和方法,可获取文件名、路径、类型(文件/文件夹)、大小等核心信息。

  4. 用ListView展示列表
    结合FutureBuilder处理异步加载的文件列表,通过ListView.builder构建可滚动的列表项。

完整代码示例

import 'dart:io';
import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Folder Viewer',
      home: FolderViewer(folderPath: r'C:\test'),
    );
  }
}

class FolderViewer extends StatefulWidget {
  final String folderPath;

  const FolderViewer({super.key, required this.folderPath});

  @override
  State<FolderViewer> createState() => _FolderViewerState();
}

class _FolderViewerState extends State<FolderViewer> {
  late Future<List<FileSystemEntity>> _filesFuture;

  @override
  void initState() {
    super.initState();
    _filesFuture = _getFolderContents();
  }

  Future<List<FileSystemEntity>> _getFolderContents() async {
    final directory = Directory(widget.folderPath);
    if (!await directory.exists()) {
      throw Exception('指定目录不存在');
    }
    // includeProperties: true 用于获取文件大小等属性
    final entities = await directory.list(includeProperties: true).toList();
    // 按文件名排序
    entities.sort((a, b) => a.path.compareTo(b.path));
    return entities;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('查看 ${widget.folderPath}')),
      body: FutureBuilder<List<FileSystemEntity>>(
        future: _filesFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting) {
            return const Center(child: CircularProgressIndicator());
          }
          if (snapshot.hasError) {
            return Center(child: Text('加载失败: ${snapshot.error}'));
          }
          final files = snapshot.data ?? [];
          return ListView.builder(
            itemCount: files.length,
            itemBuilder: (context, index) {
              final entity = files[index];
              final isDirectory = entity is Directory;
              final fileName = entity.path.split(Platform.pathSeparator).last;
              String? fileSize;
              if (entity is File) {
                fileSize = '${(entity.statSync().size / 1024).toStringAsFixed(2)} KB';
              }
              return ListTile(
                leading: Icon(isDirectory ? Icons.folder : Icons.insert_drive_file),
                title: Text(fileName),
                subtitle: Text(fileSize ?? '文件夹'),
                onTap: () {
                  if (isDirectory) {
                    Navigator.push(
                      context,
                      MaterialPageRoute(
                        builder: (context) => FolderViewer(folderPath: entity.path),
                      ),
                    );
                  }
                },
              );
            },
          );
        },
      ),
    );
  }
}

注意事项

  • 路径转义:Windows路径的反斜杠需转义,可使用原始字符串(前缀r)如r'C:\test',或写成'C:\\test'。
  • 权限问题:访问系统保护目录(如C:\Windows)时,需以管理员身份运行Flutter应用,否则会出现权限不足错误。
  • 异步处理:IO操作耗时,必须用异步方式处理,避免阻塞UI线程。

内容的提问来源于stack exchange,提问作者DktPhl2018

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 20:04:50