Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use precacheImage function in flutter?

Unable to use precacheImage function to load and cache the local images from assets to GridView or ListView in flutter.

ISSUE: When scrolling the list, images always reload.

class AppLandingPage extends StatelessWidget {
  final String title;

  AppLandingPage({Key key, this.title}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        drawer: DrawerPage(),
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return getToolbarWidget("Home title");
          },
          body: setDataToContainer(),
        ));
  }
}

Container setDataToContainer() {
  return Container(
    color: Colors.white,
    margin: EdgeInsets.only(left: 4.0, right: 4, bottom: 4, top: 4),
    child: CustomScrollView(
      slivers: <Widget>[
        SliverList(
          delegate: SliverChildListDelegate(
            [
              HeaderWidget("Header 1"),
            ],
          ),
        ),
        SliverGrid(
          gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          delegate: SliverChildListDelegate(
            [
              BodyWidget("title", "key_x", "pnl.svg"),
              BodyWidget("title2", "key_x", "cls.svg"),
              BodyWidget(
                  "title3", "key_x", "irr.svg"),
              BodyWidget(
                  "title4", "key_x", "icp.svg"),
            ],
          ),
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            [
              HeaderWidget("Header 2"),
            ],
          ),
        ),
        SliverGrid(
          gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          delegate: SliverChildListDelegate(
            [
              BodyWidget("title5", "key_x", "ict.svg"),
              BodyWidget("title6", "key_x", "icc.svg"),
            ],
          ),
        ),
        SliverList(
          delegate: SliverChildListDelegate(
            [
              HeaderWidget("Others"),
            ],
          ),
        ),
        SliverGrid(
          gridDelegate:
          SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
          delegate: SliverChildListDelegate(
            [
              BodyWidget("title7", "key_x", "icd.svg"),
              BodyWidget("title8", "6", "ici.svg"),
            ],
          ),
        ),
      ],
    ),
  );
}

class HeaderWidget extends StatelessWidget {
  final String text;

  HeaderWidget(this.text);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 10.0, right: 10, bottom: 2, top: 20),
      child: Text(
        text.toUpperCase(),
        style: TextStyle(
            color: hexToColor(themeColor1),
            fontSize: 16,
            fontWeight: FontWeight.bold),
      ),
      color: Colors.white,
    );
  }
}

class BodyWidget extends StatelessWidget {
  final String imagePath;
  final String title;
  final String navigationKey;

  BodyWidget(this.title, this.navigationKey, this.imagePath);

  @override
  Widget build(BuildContext context) {
    return Container(
        alignment: Alignment.center,
        child: Card(
          color: hexToColor(themeColor1),
          elevation: 5,
          child: InkWell(
            onTap: () {
              navigateToView(context, navigationKey);
            },
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.topCenter,
                  child: Container(
                    margin: EdgeInsets.only(top: 40),
                    child: SvgPicture.asset(
                      "assets/images/$imagePath",
                      color: Colors.white,
                      width: 35,
                      height: 35,
                    ),
                  ),
                ),
                Align(
                  alignment: Alignment.bottomCenter,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.stretch,
                    verticalDirection: VerticalDirection.up,
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.all(10),
                        color: Colors.black.withOpacity(.2),
                        child: Text(
                          title,
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 14,
                              fontWeight: FontWeight.normal),
                        ),
                      )
                    ],
                  ),
                ),
              ],
            ),
          ),
        ));
  }

  void navigateToView(BuildContext context, String navigationKey) {

    Navigator.push(
      context,
      PageRouteBuilder(
        pageBuilder: (context, animation1, animation2) {
          return NewSections();
        },
        transitionsBuilder: (context, animation1, animation2, child) {
          return FadeTransition(
            opacity: animation1,
            child: child,
          );
        },
        transitionDuration: Duration(milliseconds: 600),
      ),
    );
  }
}
like image 528
jazzbpn Avatar asked May 09 '19 04:05

jazzbpn


People also ask

What is precacheimage in flutter?

It shows when the user uses the precacheImage function, the image load faster from the assets folder in your flutter application. So please try it. If I got something wrong? Let me know in the comments.

What is precacheimage in C++?

precacheImage takes ImageProvider and context as required arguments and returns Future<void> This strategy prefetches the image into the image cache and afterward at whatever point the image is utilized, it will be stacked a lot quicker. Nonetheless, ImageCache doesn’t permit to hold extremely huge pictures.

How to create a basic function in flutter?

You can create a simple basic function in Flutter as given below. As you see void is what you return in the function, printText is the name of the function and the String text is the parameter. You can also ditch void and write the function as given below.

How does the imagecache work?

The ImageCache will find the image as long as both images share the same key, and the image is held by the cache. The cache may refuse to hold the image if it is disabled, the image is too large, or some other criteria implemented by a custom ImageCache implementation.


2 Answers

I'm not sure how to solve the preloading issue. However you could use a AutomaticKeepAliveClientMixin for your Stateful Widget's state class (the one containing your grid objects. You will have to make your BodyWidget a StatefulWidget) so that you only load each image once and not re-render when the widget goes out of visibility.

class _WidgetState extends State<Widget> with AutomaticKeepAliveClientMixin<Widget>{
….
….
@override
@mustCallSuper
Widget build(BuildContext context)….
….
….
@override
bool get wantKeepAlive => true;
}'

Hope that helps!

like image 34
Joshua Pocsidio Avatar answered Sep 29 '22 15:09

Joshua Pocsidio


Instead of calling precacheImage() inside initState(), you should do it like this:

Image myImage;

@override
void initState() {
  super.initState();
  myImage= Image.asset(path);
}
  
@override
void didChangeDependencies() {
  super.didChangeDependencies();
  precacheImage(myImage.image, context);
}
like image 69
Ethirallan Avatar answered Sep 29 '22 15:09

Ethirallan