L.G*_*yal 7 dart flutter flutter-dependencies
我有一个像“https://example.com/xyz.jpg”这样的图片网址。现在我想把图像放在一个文件类型变量中;
沿着这些路线的东西:
File f = File("https://example.com/xyz.jpg");
Run Code Online (Sandbox Code Playgroud)
重点是从给定的 URL 获取图像并将其保存为 File 变量。我怎么能这样做?我在互联网上搜索了许多解决方案,但没有直接的方法。
PS:我可能遗漏了一些类似回答的问题,所以请告诉我可以找到它的链接。
编辑:我使用文件类型变量将它传递到共享函数中。 这是我正在使用的库。
这是我当前的分享按钮点击代码
if (file != null) {
ShareExtend.share(file.path, "image",
sharePanelTitle: "share image title",
subject: "share image subject");
}
Run Code Online (Sandbox Code Playgroud)
谢谢你的帮助。
您需要下载图像并创建一个空文件,然后用图像数据填充文件:
import 'dart:io';
import 'package:http/http.dart' as http;
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> _fileFromImageUrl() async {
final response = await http.get('https://example.com/xyz.jpg');
final documentDirectory = await getApplicationDocumentsDirectory();
final file = File(join(documentDirectory.path, 'imagetest.png'));
file.writeAsBytesSync(response.bodyBytes);
return file;
}
Run Code Online (Sandbox Code Playgroud)
小智 5
import 'dart:io';
import 'package:dio/dio.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
Future<File> getImage({required String url}) async {
/// Get Image from server
final Response res = await Dio().get<List<int>>(
url,
options: Options(
responseType: ResponseType.bytes,
),
);
/// Get App local storage
final Directory appDir = await getApplicationDocumentsDirectory();
/// Generate Image Name
final String imageName = url.split('/').last;
/// Create Empty File in app dir & fill with new image
final File file = File(join(appDir.path, imageName));
file.writeAsBytesSync(res.data as List<int>);
return file;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3929 次 |
最近记录: |