Preload Image Without BuildContext

杀马特。学长 韩版系。学妹 提交于 2021-01-28 21:33:53

问题


Is there a way to load images in Flutter in a function without access to a BuildContext?

Flutter can preload images with precacheImage() which requires a BuildContext and is inconvenient to use.

I would like to load images in the initState() method of a StatefulWidget which precacheImage() does not support.

There is an open issue about preloading images that suggests loading images without a BuildContext is not currently supported.

https://github.com/flutter/flutter/issues/26127


回答1:


I know two workarounds, first one is initstate "delayed" like so :

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var image;

  @override
  void initState() {
    super.initState();
    Future.delayed(Duration.zero).then((_) {
      //Your code here
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

Second way is to use didChangeDependencies like so :

import 'package:flutter/material.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  var image;

  bool init = true;  

  @override
  void didChangeDependencies() {
    if (init) {
      init = false;
      //your code here
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return Container();
  }
}

init boolean is to prevent didChangeDependecies from running same code so many time as it reruns alot

Hope this helps.



来源:https://stackoverflow.com/questions/62478972/preload-image-without-buildcontext

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!