如何在flutter web中支持HTTP头NetworkImage

7cjasjjr  于 2023-02-09  发布在  Flutter
关注(0)|答案(3)|浏览(177)

我试着从flutter web中获取一些需要添加标题的图片。我使用了cached_network_image:^2.5.1并且它不完全支持web,而且Image.network在web上运行flutter时,似乎没有使用标题。这两种方式在Android版本上都能成功运行。

environment:
  sdk: ">=2.7.0 <3.0.0"

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.0.4, on Microsoft Windows [Version 10.0.19042.985], locale en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 30.0.3)
[√] Chrome - develop for the web
[√] Android Studio (version 4.1.0)
[√] IntelliJ IDEA Ultimate Edition (version 2020.1)
[√] Connected device (3 available)

• No issues found!
gab6jxml

gab6jxml1#

使用缓存的网络映像:3.0.0我通过使用CachedNetworkImageProvider类使其能够添加头文件。

CachedNetworkImageProvider(
              "${IOConfig.apiUrl}",
              headers: {"Authorization": "Bearer $apiToken",
                "Access-Control-Allow-Headers": "Access-Control-Allow-Origin, Accept"}                                                
             ,imageRenderMethodForWeb: ImageRenderMethodForWeb.HttpGet)

我不得不用一个参数来启动它,以更改Web渲染器

flutter run -d chrome --web-renderer html
wvmv3b1j

wvmv3b1j2#

这种特殊的限制很可能是由于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);
    });
  }

现在我们可以使用生成的syntetic 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...'),
      ),
    );
  }
}
klh5stk1

klh5stk13#

我建议不要将图像转换为blob,而只将原始字节传递给内存图像:

Uint8List? _imageBytes;

  void loadImage(String url, Map<String, String>? headers) async {
    final res = await http.get(Uri.parse(url), headers: headers);
    setState(() {
      _imageBytes = res.bodyBytes;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Center(
        child: _imageBytes == null ? Text('Loading...') : Image.memory(_imageBytes!),
      ),
    );
  }

记住使用ImageerrorBuilder参数,以防请求失败或不包含有效图像。

相关问题