Flutter存储管理插件storage_manager的使用
Flutter存储管理插件storage_manager的使用
Features
storage_manager
是一个用于在线 FirebaseStorage
和离线 Shared Preferences
的存储管理插件。
Getting Started
在您的 Dart 文件中添加以下导入行:
import 'package:storage_manager/storage_manager.dart';
Usage
该插件可以将图像、视频、文本(纯文本或 JSON)和数据(字节)保存到设备本地存储 shared_preferences
或 Firebase Cloud Storage firebase_storage
,并使用最新的依赖项。
Get Methods
获取文件(图像、字符串、视频、JSON 或字节)从给定路径
final file = await StorageProvider.get('/collectionName/fileName.png');
获取图像从给定路径
Uint8List? image = await StorageProvider.getImage('/collectionName/fileName.png');
获取视频从给定路径
Uint8List? video = await StorageProvider.getVideo('/collectionName/fileName.mp4');
获取字符串从给定路径
String? text = await StorageProvider.getString('/collectionName/fileName.txt');
获取 JSON 从给定路径
Map<String, dynamic>? json = await StorageProvider.getJson('/collectionName/fileName.json');
从本地存储获取图像
Uint8List? image = await StorageProvider.getLocalImage('/collectionName/fileName.png');
从本地存储获取视频
Uint8List? video = await StorageProvider.getLocalVideo('/collectionName/fileName.mp4');
从本地存储获取字符串
String? text = await StorageProvider.getLocalString('/collectionName/fileName.txt');
从本地存储获取 JSON
Map<String, dynamic>? json = await StorageProvider.getLocalJson('/collectionName/fileName.json');
Remove Methods
从存储或本地路径删除文件
bool success = await StorageProvider.remove('/collectionName/fileName.png');
从存储 URL 删除文件
bool success = await StorageProvider.removeUrl('url');
Upload Methods
上传动态文件(图像、视频、字符串、JSON 或字节)到给定路径
String url = await StorageProvider.save('/collectionName/fileName.png', image);
上传图像到给定路径
String url = await StorageProvider.saveImage('/collectionName/fileName.png', image);
上传视频到给定路径
String url = await StorageProvider.saveVideo('/collectionName/fileName.mp4', video);
上传 JSON 到给定路径
String url = await StorageProvider.saveBytes('/collectionName/fileName.json', json);
直接将图像保存到本地存储
String url = await StorageProvider.saveLocalImage('/collectionName/fileName', image);
直接将视频保存到本地存储
String url = await StorageProvider.saveLocalVideo('/collectionName/fileName', video);
直接将字符串保存到本地存储
String url = await StorageProvider.saveLocalString('/collectionName/fileName', text);
直接将 JSON 保存到本地存储
String url = await StorageProvider.saveLocalJson('/collectionName/fileName', json);
Integrated Image Picker Feature
从图库或相机选择图像
if (await StorageProvider.selectImages()) {
List<XFile> images = StorageProvider.selectedAssets;
} else {
print('User cancelled selection');
}
上传选定的图像到给定路径
List<XFile> images = StorageProvider.selectedAssets;
List<String> urls = await StorageProvider.save('/collectionName/', images);
从图库选择并上传图像
String url = await StorageProvider.selectAndUpload();
Customizations
自定义图像选择器 getSource
函数和 showDataUploadProgress
函数
StorageProvider.configure(
context: context,
showProgress: true,
getImageSource: () async => await showDialog<ImageSource>(
context: context,
builder: (context) => SimpleDialog(
title: const Text("Select image source"),
children: [
ListTile(
title: const Text("Camera"),
leading: const Icon(Icons.camera_alt),
onTap: () => Navigator.pop(context, ImageSource.camera),
),
ListTile(
title: const Text("Gallery"),
leading: const Icon(Icons.photo),
onTap: () => Navigator.pop(context, ImageSource.gallery),
),
],
),
),
showDataUploadProgress: (uploadTask) async {
return await showDialog(
context: context,
barrierDismissible: true,
builder: (context) {
return StreamBuilder<TaskSnapshot>(
stream: uploadTask.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
return AlertDialog(
title: const Text('Uploading...'),
content: ProgressFromUploadTask(
task: uploadTask,
onDone: () {
Navigator.pop(context);
},
),
);
} else {
return const AlertDialog(
title: Text('Waiting...'),
content: LinearProgressIndicator(),
);
}
},
);
},
);
},
);
Rendering Images from Storage
Flutter Web 需要额外的脚本
在 index.html
文件的 body
底部添加以下脚本:
<script type="text/javascript">
window.flutterWebRenderer = "html";
</script>
Additional Information
此包假设已完全配置 Firebase 存储和权限。我们推荐使用 flutterfire
来配置您的项目。更多信息请访问:https://firebase.flutter.dev/docs/overview/
dart pub global activate flutterfire_cli
flutterfire configure
示例代码
以下是 storage_manager
的一个完整示例:
import 'dart:typed_data';
import 'package:firebase_storage/firebase_storage.dart';
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'package:storage_manager/storage_manager.dart';
void main() async {
WidgetsFlutterBinding.ensureInitialized();
// Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Storage Manager Demo',
theme: ThemeData(
primarySwatch: Colors.deepPurple,
),
home: const MyHomePage(title: 'Storage Manager Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<String> links = [];
String path = "/images/";
bool showProgress = false;
List<XFile>? selectedAssets = [];
int maxImagesCount = 10;
@override
Widget build(BuildContext context) {
StorageProvider.configure(
context: context,
showProgress: true,
getImageSource: () async => await showDialog<ImageSource>(
context: context,
builder: (context) => SimpleDialog(
title: const Text("Select image source"),
children: [
ListTile(
title: const Text("Camera"),
leading: const Icon(Icons.camera_alt),
onTap: () => Navigator.pop(context, ImageSource.camera),
),
ListTile(
title: const Text("Gallery"),
leading: const Icon(Icons.photo),
onTap: () => Navigator.pop(context, ImageSource.gallery),
),
],
),
),
showDataUploadProgress: (uploadTask) async {
return await showDialog(
context: context,
barrierDismissible: true,
builder: (context) {
return StreamBuilder<TaskSnapshot>(
stream: uploadTask.snapshotEvents,
builder: (context, snapshot) {
if (snapshot.hasData) {
return AlertDialog(
title: const Text('Uploading...'),
content: ProgressFromUploadTask(
task: uploadTask,
onDone: () {
Navigator.pop(context);
},
),
);
} else {
return const AlertDialog(
title: Text('Waiting...'),
content: LinearProgressIndicator(),
);
}
},
);
},
);
},
);
return Scaffold(
backgroundColor: Colors.grey[900],
appBar: AppBar(
title: Text(widget.title),
),
body: ListView(
children: [
Wrap(
alignment: WrapAlignment.center,
spacing: 20,
runSpacing: 20,
children: [
SizedBox(
width: 500,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 20),
const Text("Selected files", style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
...selectedAssets
?.map((e) => Card(
child: ListTile(
title: Text(e.path),
subtitle: SizedBox(
width: 400,
height: 400,
child: FutureBuilder(
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const CircularProgressIndicator();
}
return Image.memory(
snapshot.data as Uint8List,
fit: BoxFit.contain,
);
},
future: e.readAsBytes(),
),
),
),
))
.toList() ??
[],
const SizedBox(height: 20),
],
),
),
SizedBox(
width: 500,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const SizedBox(height: 20),
const Text("Uploaded files links", style: TextStyle(color: Colors.white), textAlign: TextAlign.center),
...links
.map((e) => Card(
child: ListTile(
title: Text(e),
subtitle: Image.network(
e,
width: 400,
height: 400,
fit: BoxFit.contain,
),
),
))
.toList(),
const SizedBox(height: 20),
],
),
)
],
),
],
),
floatingActionButton: Column(
mainAxisSize: MainAxisSize.min,
children: [
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple,
),
child: const Text("Select images", style: TextStyle(color: Colors.white)),
onPressed: () async {
await StorageProvider.selectAssets(backgroundColor: Colors.grey[900]!);
setState(() {
selectedAssets = StorageProvider.selectedAssets;
});
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple,
),
child: const Text("Upload selected images", style: TextStyle(color: Colors.white)),
onPressed: () async {
links = await StorageProvider.uploadSelectedAssets(path, context: context, showProgress: true);
setState(() {});
},
),
),
Padding(
padding: const EdgeInsets.all(8.0),
child: ElevatedButton(
style: ElevatedButton.styleFrom(
backgroundColor: Colors.deepPurple,
),
child: const Text("Select and upload images", style: TextStyle(color: Colors.white)),
onPressed: () async {
await StorageProvider.selectAndUpload(path);
setState(() {
links = StorageProvider.links;
});
},
),
),
],
),
);
}
}
以上代码展示了如何使用 storage_manager
插件来选择、上传和显示图像。希望这对您有所帮助!
更多关于Flutter存储管理插件storage_manager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter存储管理插件storage_manager的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
当然,下面是一个关于如何使用Flutter的storage_manager
插件进行存储管理的代码示例。请注意,实际使用中可能需要根据具体的插件版本和Flutter环境进行微调。假设storage_manager
插件提供了基本的文件读写功能,以下是一个简单的示例:
首先,确保你已经在pubspec.yaml
文件中添加了storage_manager
依赖:
dependencies:
flutter:
sdk: flutter
storage_manager: ^x.y.z # 请替换为实际的版本号
然后,运行flutter pub get
来安装依赖。
接下来,在你的Flutter项目中,你可以按照以下方式使用storage_manager
插件:
import 'package:flutter/material.dart';
import 'package:storage_manager/storage_manager.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: StorageManagerDemo(),
);
}
}
class StorageManagerDemo extends StatefulWidget {
@override
_StorageManagerDemoState createState() => _StorageManagerDemoState();
}
class _StorageManagerDemoState extends State<StorageManagerDemo> {
final StorageManager _storageManager = StorageManager();
String _readFileContent = '';
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Storage Manager Demo'),
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
decoration: InputDecoration(labelText: 'Enter text to save'),
onChanged: (text) {
// This is where you might want to save the text to storage
// For simplicity, we'll save it when the button is pressed
},
),
SizedBox(height: 16),
ElevatedButton(
onPressed: () async {
// Save text to storage
String textToSave = 'Hello, Flutter Storage Manager!'; // Replace with actual text input
await _storageManager.writeFile('example.txt', textToSave);
// Read file from storage
String fileContent = await _storageManager.readFile('example.txt');
setState(() {
_readFileContent = fileContent;
});
},
child: Text('Save and Read File'),
),
SizedBox(height: 16),
Text('File Content:', style: TextStyle(fontWeight: FontWeight.bold)),
Text(_readFileContent),
],
),
),
);
}
}
注意:
- 上面的代码示例假设
StorageManager
类提供了writeFile
和readFile
方法。实际使用时,你需要查阅storage_manager
插件的文档以了解具体的方法和API。 StorageManager
类的实例化和方法调用可能需要根据实际插件的实现进行调整。- 由于
storage_manager
不是一个官方或广泛认知的Flutter插件名称,因此上面的代码是基于假设的API设计。如果你使用的是特定的第三方插件,请参考该插件的官方文档。
如果storage_manager
插件的API与上述假设不同,你可能需要查阅该插件的GitHub仓库或pub.dev页面上的文档来获取正确的使用方法。