我尝试使用
path_provider
遵循与您类似的方法来获取文件。然而,即使使用
getExternalStorageDirectory()
,该插件也只能获取应用程序目录,这种行为也在
Stack Overflow post中指出。
相反,我使用
ext_storage
访问设备存储。
此示例应用程序演示了如何使用
ext_storage
在设备的/Download文件夹中获取文件,使用
permission_handler
处理权限、文件扩展名检查,并在GridView上显示路径中的图像。
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:ext_storage/ext_storage.dart';
import 'package:permission_handler/permission_handler.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
Future _futureGetPath;
List<dynamic> listImagePath = List<dynamic>();
var _permissionStatus;
@override
void initState() {
super.initState();
_listenForPermissionStatus();
_futureGetPath = _getPath();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Expanded(
flex: 1,
child: FutureBuilder(
future: _futureGetPath,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
var dir = Directory(snapshot.data);
print('permission status: $_permissionStatus');
if (_permissionStatus) _fetchFiles(dir);
return Text(snapshot.data);
} else {
return Text("Loading");
}
},
),
),
Expanded(
flex: 19,
child: GridView.count(
primary: false,
padding: const EdgeInsets.all(20),
crossAxisSpacing: 10,
mainAxisSpacing: 10,
crossAxisCount: 3,
children: _getListImg(listImagePath),
),
)
],
),
);
}
void _listenForPermissionStatus() async {
final status = await Permission.storage.request().isGranted;
setState(() => _permissionStatus = status);
}
Future<String> _getPath() {
return ExtStorage.getExternalStoragePublicDirectory(
ExtStorage.DIRECTORY_DOWNLOADS);
}
_fetchFiles(Directory dir) {
List<dynamic> listImage = List<dynamic>();
dir.list().forEach((element) {
RegExp regExp =
new RegExp("\.(gif|jpe?g|tiff?|png|webp|bmp)", caseSensitive: false);
if (regExp.hasMatch('$element')) listImage.add(element);
setState(() {
listImagePath = listImage;
});
});
}
List<Widget> _getListImg(List<dynamic> listImagePath) {
List<Widget> listImages = List<Widget>();
for (var imagePath in listImagePath) {
listImages.add(
Container(
padding: const EdgeInsets.all(8),
child: Image.file(imagePath, fit: BoxFit.cover),
),
);
}
return listImages;
}
}
![enter image description here](https://istack.dev59.com/1GrFK.gif)
注意,这仅涵盖在GridView上显示图像的基础知识。为了进行缩放,我建议遵循
性能最佳实践指南。