最有可能,这种限制是由于
img
HTML元素本身的定制能力降低所致。幸运的是,还有许多其他方法来显示网络图片 - 这里只列举了两个例子:
使用http软件包:
void loadImageV1(String url, Map<String, String>? headers) async {
final res = await http.get(Uri.parse(url), headers: headers);
final blob = html.Blob([res.bodyBytes]);
setState(() {
_url = html.Url.createObjectUrlFromBlob(blob);
});
}
或者使用浏览器提供的
fetch API:
void loadImageV2(String url, Map<String, String>? headers) async {
final res = await html.window.fetch(url, {'method': 'GET', 'headers': headers});
final blob = await res.blob();
setState(() {
_url = html.Url.createObjectUrlFromBlob(blob);
});
}
现在我们可以使用生成的合成URL来构造Image.Network。
以下是完整的演示:
import 'dart:html' as html;
import 'package:http/http.dart' as http;
import 'package:flutter/material.dart';
void main() => runApp(DemoApp());
class DemoApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Network Image Demo',
home: NextLabPage(),
);
}
}
const imgUrl = 'https://robohash.org/1234';
const imgHeaders = {'Accept': 'image/*', 'Accept-language': 'en'};
class NextLabPage extends StatefulWidget {
@override
_NextLabPageState createState() => _NextLabPageState();
}
class _NextLabPageState extends State<NextLabPage> {
String? _url;
@override
void initState() {
super.initState();
loadImageV1(imgUrl, imgHeaders);
}
@override
void dispose() {
if (_url != null) html.Url.revokeObjectUrl(_url!);
super.dispose();
}
void loadImageV1(String url, Map<String, String>? headers) async {
final res = await http.get(Uri.parse(url), headers: headers);
final blob = html.Blob([res.bodyBytes]);
setState(() {
_url = html.Url.createObjectUrlFromBlob(blob);
});
}
void loadImageV2(String url, Map<String, String>? headers) async {
final res = await html.window.fetch(url, {'method': 'GET', 'headers': headers});
final blob = await res.blob();
setState(() {
_url = html.Url.createObjectUrlFromBlob(blob);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: _url != null ? Image.network(_url!) : Text('Loading...'),
),
);
}
}
cached_network_image_platform_interface/cached_network_image_platform_interface.dart
- agfe2