Open In App

Flutter – Lazy Loader

Improve
Improve
Like Article
Like
Save
Share
Report

The Lazy loader is a wrapper to the ScrollView that enables lazy loading. It is very useful in situations where the application’s intent is to show endless content in a ListView. For instance, Instagram, Facebook, and most social networking platforms use them to deliver an endless stream of content.

In this article, we will look into the process of implementing Lazy loader to an application by building a simple app with endless content. For the sake of simplicity, we will use a single content and make a copy of it for the rest of the content in the app. To do so follow the below steps:

  • Add the dependency to the pubspec.yaml file
  • Import the dependency to the main.dart file
  • Use a StatefulWidget to extend it to structure the Homepage
  • Call the LazyLoaderScrollView in the body of the Homepage
  • Design the content of the Homepage

Let’s look into the steps in detail.

Adding the dependency:

The Lazy loader can be added to the dependencies of the pubspec.yaml file as shown below:

dependency

Importing the dependency:

The following line of code can be added to the main.dart file to import the lazy_load_scrollview dependency:

import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';

Creating the Homepage:

A StatefulWidget can be extended to form a simple Homepage for the application as shown below:

Dart




class MyApp extends StatelessWidget {
  //root of the application
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Example',
      home: new MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  final String title;
  
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  List<int> data = [];
  int currentLength = 0;
  
  final int increment = 10;
  bool isLoading = false;
  
  @override
  void initState() {
    _loadMore();
    super.initState();
  }
  
  Future _loadMore() async {
    setState(() {
      isLoading = true;
    });
  
    // dummy delay
    await new Future.delayed(const Duration(seconds: 2));
    for (var i = currentLength; i <= currentLength + increment; i++) {
      data.add(i);
    }
    setState(() {
      isLoading = false;
      currentLength = data.length;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Colors.green,
      ),
      // contents of the app goes here
      body:
      ),
    );
  }
}


Calling the LazyLoaderScrollView:

The LazyLoaderScrollView is a method provided by the lazy_load_scrollview package that is used to implement lazy loading to the app and can be implemented as shown below:

Dart




LazyLoadScrollView(
        isLoading: isLoading,
        onEndOfPage: () => _loadMore(),
        child: ListView.builder(
          itemCount: data.length,
          itemBuilder: (context, position) {
            return DemoItem(position);


Designing the Content:

Here again, a StatelessWidget can be extended to a body of text content that gets loaded infinitely by the app as shown below:

Dart




class DemoItem extends StatelessWidget {
  final int position;
  
  const DemoItem(
      this.position, {
        Key key,
      }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  color: Colors.deepOrange,
                  height: 40.0,
                  width: 40.0,
                ),
                SizedBox(width: 8.0),
                Text("Item $position"),
              ],
            ),
            Text(
                "GeeksforGeeks.org was created with a goal "
                    "in mind to provide well written, well "
                    "thought and well explained solutions for selected"
                    " questions. The core team of five super geeks"
                    " constituting of technology lovers and computer"
                    " science enthusiasts have been constantly working"
                    " in this direction ."),
          ],
        ),
      ),
    );
  }
}


Complete Source Code:

Dart




import 'package:flutter/material.dart';
import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';
  
void main() => runApp(new MyApp());
  
class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Example',
      home: new MyHomePage(title: 'GeeksForGeeks'),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  
  final String title;
  
  @override
  _MyHomePageState createState() => new _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  List<int> data = [];
  int currentLength = 0;
  
  final int increment = 10;
  bool isLoading = false;
  
  @override
  void initState() {
    _loadMore();
    super.initState();
  }
  
  Future _loadMore() async {
    setState(() {
      isLoading = true;
    });
  
    // Add in an artificial delay
    await new Future.delayed(const Duration(seconds: 2));
    for (var i = currentLength; i <= currentLength + increment; i++) {
      data.add(i);
    }
    setState(() {
      isLoading = false;
      currentLength = data.length;
    });
  }
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        backgroundColor: Colors.green,
      ),
      body: LazyLoadScrollView(
        isLoading: isLoading,
        onEndOfPage: () => _loadMore(),
        child: ListView.builder(
          itemCount: data.length,
          itemBuilder: (context, position) {
            return DemoItem(position);
          },
        ),
      ),
    );
  }
}
  
class DemoItem extends StatelessWidget {
  final int position;
  
  const DemoItem(
      this.position, {
        Key key,
      }) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Card(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: <Widget>[
                Container(
                  color: Colors.deepOrange,
                  height: 40.0,
                  width: 40.0,
                ),
                SizedBox(width: 8.0),
                Text("Item $position"),
              ],
            ),
            Text(
                "GeeksforGeeks.org was created with a goal "
                    "in mind to provide well written, well "
                    "thought and well explained solutions for selected"
                    " questions. The core team of five super geeks"
                    " constituting of technology lovers and computer"
                    " science enthusiasts have been constantly working"
                    " in this direction ."),
          ],
        ),
      ),
    );
  }
}


Output:



Last Updated : 28 Oct, 2020
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads