例如,使用 dio 插件
dio使用大尺寸文件下载器
网址链接:https://pub.dev/packages/dio
举例
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:dio/dio.dart';
import 'package:path_provider/path_provider.dart';
class LargeFileMain extends StatefulWidget {
@override
State<StatefulWidget> createState() => _LargeFileMain();
}
class _LargeFileMain extends State<LargeFileMain> {
final imgUrl =
'http://your_url.com/file.mp4';
bool downloading = false;
var progressString = "";
var file;
Future<void> downloadFile() async {
Dio dio = Dio();
try {
var dir = await getApplicationDocumentsDirectory();
await dio.download(imgUrl, '${dir.path}/myimage.jpg',
onReceiveProgress: (rec, total) {
print('Rec: $rec , Total: $total');
file = '${dir.path}/myimage.jpg';
setState(() {
downloading = true;
progressString = ((rec / total) * 100).toStringAsFixed(0) + '%';
});
});
} catch (e) {
print(e);
}
setState(() {
downloading = false;
progressString = 'Completed';
});
print('Download completed');
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Large File Example'),
),
body: Center(
child: downloading
? Container(
height: 120.0,
width: 200.0,
child: Card(
color: Colors.black,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
height: 20.0,
),
Text(
'Downloading File: $progressString',
style: TextStyle(
color: Colors.white,
),
)
],
),
),
)
: FutureBuilder(
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
print('none');
return Text('No Data');
case ConnectionState.waiting:
print('waiting');
return CircularProgressIndicator();
case ConnectionState.active:
print('active');
return CircularProgressIndicator();
case ConnectionState.done:
print('done');
if (snapshot.hasData) {
return snapshot.data;
}
}
return Text('No Data');
},
future: downloadWidget(file),
)),
floatingActionButton: FloatingActionButton(
onPressed: () {
downloadFile();
},
child: Icon(Icons.file_download),
),
);
}
Future<Widget> downloadWidget(String filePath) async {
File file = File(filePath);
bool exist = await file.exists();
if (exist) {
return Center(
// your video file using widget
);
} else {
return Text('No Data');
}
}
}