Flutter – Cargador perezoso

El cargador diferido es un contenedor para ScrollView que permite la carga diferida. Es muy útil en situaciones en las que la intención de la aplicación es mostrar un sinfín de contenido en un ListView . Por ejemplo, Instagram , Facebook y la mayoría de las plataformas de redes sociales las utilizan para ofrecer un flujo interminable de contenido.

En este artículo, analizaremos el proceso de implementación de Lazy Loader en una aplicación mediante la creación de una aplicación simple con contenido ilimitado. En aras de la simplicidad, utilizaremos un único contenido y haremos una copia del mismo para el resto del contenido de la aplicación. Para hacerlo, siga los siguientes pasos:

  • Agregue la dependencia al archivo pubspec.yaml
  • Importe la dependencia al archivo main.dart
  • Use un StatefulWidget para extenderlo y estructurar la página de inicio
  • Llame a LazyLoaderScrollView en el cuerpo de la página de inicio
  • Diseñar el contenido de la Homepage

Veamos los pasos en detalle.

Agregando la dependencia:

El cargador diferido se puede agregar a las dependencias del archivo pubspec.yaml como se muestra a continuación:

dependency

Importando la dependencia:

La siguiente línea de código se puede agregar al archivo main.dart para importar la dependencia lazy_load_scrollview :

import 'package:lazy_load_scrollview/lazy_load_scrollview.dart';

Creación de la página de inicio:

Un StatefulWidget se puede ampliar para formar una página de inicio simple para la aplicación, como se muestra a continuación:

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

Llamando a LazyLoaderScrollView:

LazyLoaderScrollView es un método proporcionado por el paquete lazy_load_scrollview que se usa para implementar la carga diferida en la aplicación y se puede implementar como se muestra a continuación:

Dart

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

Diseño del contenido:

Aquí nuevamente, un StatelessWidget se puede extender a un cuerpo de contenido de texto que la aplicación carga infinitamente como se muestra a continuación:

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 ."),
          ],
        ),
      ),
    );
  }
}

Código fuente completo:

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 ."),
          ],
        ),
      ),
    );
  }
}

Producción:

Publicación traducida automáticamente

Artículo escrito por ddeevviissaavviittaa y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *