为什么在颤振中使用图像网络时 gif 渲染没有停止

时间:2021-07-30 17:38:02

标签: flutter

现在我正在使用此代码在颤振中加载 gif:

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:flutter_hooks/flutter_hooks.dart';

class LearnApp extends HookWidget {

  var gifUrl = "https://tva1.sinaimg.cn/mw690/006v119zly1gsu8ni6jbbg30a007q1l2.gif";

  Widget loadGif() {
    Completer<Size> completer = Completer();
    Image image = Image.network(gifUrl,
        frameBuilder: (ctx, child, frame, _) {
      if (frame == null) {
        if (!completer.isCompleted) {
          completer.completeError("error");
        }
        return child;
      } else {
        return child;
      }
    });

    image.image.resolve(ImageConfiguration()).addListener(
          ImageStreamListener((ImageInfo image, bool synchronousCall) {
            var myImage = image.image;
            Size size = Size(myImage.width.toDouble(), myImage.height.toDouble());
            if (!completer.isCompleted) {
              completer.complete(size);
            }
          }, onError: (object, stacktrace) {
            if (!completer.isCompleted) {
              completer.completeError(object);
            }
          }),
        );
    return FutureBuilder<Size>(
      future: completer.future,
      builder: (BuildContext buildContext, AsyncSnapshot<Size> snapshot) {
        if (snapshot.hasData) {
          return Image.network(
            gifUrl,
            frameBuilder: (ctx, child, frame, _) {
              if (frame == null) {
                return Text("dd");
              }
              return child;
            },
          );
        } else if (snapshot.hasError) {
          return Text("error");
        } else {
          return Text("dd");
        }
      },
    );;
  }

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text("widget title"),
      ),
      body: SafeArea(child: loadGif()),
    );
  }
}

退出 gif 页面时,GUI 渲染仍在运行(在 gif 页面时,渲染过程总是刷新以显示 gif 动画,但退出 gif 页面时,渲染会停止)。我正在跟踪代码,发现 ImageStreamListener 仍然处于活动状态,为什么会发生这种情况,我应该怎么做才能解决这个问题?

尝试 1:我尝试在 listener 完成后删除 Completer

if (completer.isCompleted) {
      image.image.resolve(ImageConfiguration()).removeListener(listener);
}

退出 gif 页面时停止渲染似乎不像预期的那样工作。

0 个答案:

没有答案