Most likely, this particular limitation is due to the reduced customization capabilities of the img
HTML-element itself. Fortunately, there are many other ways to display network images - here are just two examples:
Using http package:
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);
});
}
or using exposed by browser 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);
});
}
And now we can use generated syntetic url with Image.Network constructor.
Here is full demo:
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...'),
),
);
}
}
import package:cached_network_image_platform_interface/cached_network_image_platform_interface.dart
– Goaltender