构建实用的Flutter文件列表:从简到繁的完美演进
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// 此处省略其他代码...
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FileListPage(),
);
}
}
class FileListPage extends StatefulWidget {
@override
_FileListPageState createState() => _FileListPageState();
}
class _FileListPageState extends State<FileListPage> {
List<FileSystemEntity> _filesAndDirectories = [];
@override
void initState() {
super.initState();
_refreshFilesAndDirectories();
}
Future<void> _refreshFilesAndDirectories() async {
final Directory directory = await getApplicationDocumentsDirectory();
_filesAndDirectories = directory.listSync();
setState(() {});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('文件列表'),
),
body: RefreshIndicator(
onRefresh: _refreshFilesAndDirectories,
child: ListView.builder(
itemCount: _filesAndDirectories.length,
itemBuilder: (context, index) {
final entity = _filesAndDirectories[index];
return ListTile(
title: Text(entity.path.split('/').last),
trailing: Icon(
entity is File ? Icons.file_download : Icons.folder,
),
onTap: () {
// 此处省略导航逻辑...
},
);
},
),
),
);
}
}
这段代码展示了如何在Flutter中创建一个简单的文件列表页面,它使用ListView.builder
来高效构建列表项,并通过RefreshIndicator
支持下拉刷新功能。代码简洁且注重实用性,是学习Flutter列表构建和基本交互的好例子。
评论已关闭