📜  Flutter – 懒加载器

📅  最后修改于: 2021-09-02 05:29:49             🧑  作者: Mango

Lazy loader 是ScrollView的包装器,可实现延迟加载。在应用程序的意图是在ListView 中显示无限内容的情况下,它非常有用。例如, InstagramFacebook和大多数社交网络平台都使用它们来提供源源不断的内容。

在本文中,我们将通过构建一个具有无限内容的简单应用程序来研究在应用程序中实现 Lazy loader 的过程。为简单起见,我们将使用单个内容,并为应用程序中的其余内容制作一个副本。为此,请执行以下步骤:

  • 将依赖添加到pubspec.yaml 文件中
  • 将依赖项导入到 main.js 中。dart文件
  • 使用StatefulWidget扩展它以构建主页
  • 调用LazyLoaderScrollView在首页的身体
  • 设计主页的内容

让我们详细看看这些步骤。

添加依赖:

Lazy loader 可以添加到pubspec.yaml 文件的依赖项中,如下所示:

依赖

导入依赖:

可以将以下代码行添加到main. dart文件以导入lazy_load_scrollview依赖项:

import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';

创建主页:

StatefulWidget可以扩展为应用程序的简单主页,如下所示:

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 {
  List 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:
      ),
    );
  }
}


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


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: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                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 ."),
          ],
        ),
      ),
    );
  }
}


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 {
  List 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: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                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 ."),
          ],
        ),
      ),
    );
  }
}


调用 LazyLoaderScrollView:

LazyLoaderScrollView是由被用来实现延迟加载到应用程序,并且可以被实现在lazy_load_scrollview包中提供的方法如下所示:

Dart

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

设计内容:

同样,StatelessWidget 可以扩展为由应用程序无限加载的文本内容正文,如下所示:

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: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                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 ."),
          ],
        ),
      ),
    );
  }
}

完整的源代码:

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 {
  List 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: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              children: [
                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 ."),
          ],
        ),
      ),
    );
  }
}

输出:

想要一个更快节奏和更具竞争力的环境来学习 Android 的基础知识吗?
单击此处前往由我们的专家精心策划的指南,旨在让您立即做好行业准备!