一,安装第三方库
地址:
https://pub.dev/packages/http
编辑pubspec.yaml:
dependencies:flutter:sdk: flutterpath_provider: ^2.1.5http: ^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});@overrideState<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"; // <-- 1var response = await get(Uri.parse(url)); // <--2var 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 internetawait Directory(firstPath).create(recursive: true); // <-- 1File file2 = new File(filePathAndName); // <-- 2file2.writeAsBytesSync(response.bodyBytes); // <-- 3return filePathAndName;}void _setImageData(filePathAndName) {setState(() {imageData = filePathAndName;dataLoaded = true;});}String imageData = '';bool dataLoaded = false;@overrideWidget 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)],),],),),);}
}