LoginSignup
2
3

More than 5 years have passed since last update.

画像のダウンロード中に別の画像を出す

Posted at

FlutterでNetworkImageクラスでサーバーから画像をダウンロードしている間別の画像を出す場合、方法について共有します。

ImageProviderの派生クラスNetoworkImageクラスではローデイング画像を出せない

実装を見ている限りですが、画像のダウンロード処理は await しているぽいでの別の画像をだすことはできません。

↓実際の内部実装


Future<ui.Codec> _loadAsync(NetworkImage key) async {
    assert(key == this);

    final Uri resolved = Uri.base.resolve(key.url);
    final HttpClientRequest request = await _httpClient.getUrl(resolved);
    headers?.forEach((String name, String value) {
      request.headers.add(name, value);
    });
    final HttpClientResponse response = await request.close();
    if (response.statusCode != HttpStatus.OK)
      throw new Exception('HTTP request failed, statusCode: ${response?.statusCode}, $resolved');

    final Uint8List bytes = await consolidateHttpClientResponseBytes(response);
    if (bytes.lengthInBytes == 0)
      throw new Exception('NetworkImage is an empty file: $resolved');

    return await ui.instantiateImageCodec(bytes);
  }

解決方法

FadeInImage クラスでラップしましょう
サンプルコードはこんな感じです

new FadeInImage(
     image: NetworkImage(snapshot["image_url"]),
     fit: BoxFit.fill,
     placeholder: AssetImage("assets/loading_image.png"),
)

placeholder で別の画像を読み込んで出しましょう。

2
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
3