Ray Li
Ray Li

Reputation: 7919

Preload Image Without BuildContext

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

Upvotes: 5

Views: 1851

Answers (1)

Rechem MEG
Rechem MEG

Reputation: 309

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.

Upvotes: 1

Related Questions