flutter:用http库下载文件
一,安装第三方库
地址:
https://pub.dev/packages/http
编辑pubspec.yaml:
dependencies:
flutter:
sdk: flutter
path_provider: ^2.1.5
http: ^1.3.0
然后点击 pub get
二,代码:
import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'package:path_provider/path_provider.dart';
import 'dart:io';
class DownloadPage extends StatefulWidget {
final Map arguments;
// 为title设置一个默认参数,这样的跳转该界面时可以不传值。
DownloadPage({super.key, required this.arguments});
@override
State<DownloadPage> createState() => _DownloadPageState();
}
class _DownloadPageState extends State<DownloadPage> {
_downloadFile(String url) async {
//comment out the next two lines to prevent the device from getting
// the image from the web in order to prove that the picture is
// coming from the device instead of the web.
//var url = "https://www.tottus.cl/static/img/productos/20104355_2.jpg"; // <-- 1
var response = await get(Uri.parse(url)); // <--2
var documentDirectory = await getApplicationDocumentsDirectory();
var firstPath = documentDirectory.path + "/images";
var filePathAndName = documentDirectory.path + '/images/pic.jpg';
//comment out the next three lines to prevent the image from being saved
//to the device to show that it's coming from the internet
await Directory(firstPath).create(recursive: true); // <-- 1
File file2 = new File(filePathAndName); // <-- 2
file2.writeAsBytesSync(response.bodyBytes); // <-- 3
return filePathAndName;
}
void _setImageData(filePathAndName) {
setState(() {
imageData = filePathAndName;
dataLoaded = true;
});
}
String imageData = '';
bool dataLoaded = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.primaryContainer,
title: Text(widget.arguments["title"]),
),
body: Center(
child:Column(
children: [
ElevatedButton(
onPressed: () async {
var url="https://wx3.sinaimg.cn/mw2000/7546503fly1hzsxkui8hoj21400u0n2h.jpg";
_downloadFile(url).then((value) {
print("下载图片完整路径:");
print(value);
_setImageData(value);
});
},
child: Row(
mainAxisSize: MainAxisSize.min, // 根据内容调整大小
children: <Widget>[
Icon(Icons.add), // 图标在左侧
SizedBox(width: 10), // 可选:添加一些间隔
Text("选择文件"), // 文本在右侧
],
),
),
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.file(File(imageData), width: 600.0, height: 290.0)
],
),
],
),
),
);
}
}
三,测试效果:

浙公网安备 33010602011771号