带有延迟加载的 Flutter FutureBuilder

Flutter FutureBuilder with lazy loading

下午好。我是 flutter 的新手,我想问一下是否可以对使用 FutureBuilder 呈现的 API 检索到的数据实现延迟加载。这是我的代码。对不起 api URL 我填了假人。感谢您的第一个迭代是第 1 页(内容 1-10)。第二个迭代是嵌套的。第一个代表页面,下一个代表该页面上的10个内容。

import 'dart:convert';

import 'package:flutter/material.dart';

import 'package:statistik_malang/constants.dart';
import 'package:statistik_malang/details_screen.dart';
import 'package:statistik_malang/model_publikasi.dart';
import 'package:statistik_malang/product.dart';
import 'package:http/http.dart' as http;


void main() {
  runApp(publikasi_secondpage());
}

class publikasi_secondpage extends StatefulWidget {
  // const publikasi_secondpage({ Key? key }) : super(key: key);

  @override
  _publikasi_secondpageState createState() => _publikasi_secondpageState();
}

class _publikasi_secondpageState extends State<publikasi_secondpage> {
  

  Future<List<Publikasimod>> getPublicationAll() async {
    String apiURL =
        "link of api";

    var apiResult = await http.get(Uri.parse(apiURL));
    var jsonObject = json.decode(apiResult.body);
    List<dynamic> listpublikasi = (jsonObject as Map<String, dynamic>)["data"];
    
// content in page 1 (1 to 10)    
List<Publikasimod> publikasimods = [];
    for (int i = 0; i < listpublikasi[1].length; i++) {
      publikasimods.add(Publikasimod.createPublikasimod(listpublikasi[1][i]));
    }

    
// content in page i (11-20, 21-30, ...) 
    for (int i = 2; i < listpublikasi[0]["pages"] + 1; i++) {
      String apiURL2 =
          "link of api";

      var apiResult2 = await http.get(Uri.parse(apiURL2));
      var jsonObject2 = json.decode(apiResult2.body);
      List<dynamic> listberita2 = (jsonObject2 as Map<String, dynamic>)["data"];

      for (int j = 0; j < listberita2[1].length; j++) {
        
        publikasimods.add(Publikasimod.createPublikasimod(listberita2[1][j]));
      }
    }
   
    return publikasimods;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text("Daftar Publikasi Terbaru"),
        ),
        body: FutureBuilder(
          future: getPublicationAll(),
          builder: (context, snapshot) {
            if (snapshot.error != null) {
              return Column(
                children: [
                  Text("tidak ada koneksi, mohon periksa koneksi internet anda")
                ],
              );
            } else if (snapshot.connectionState == ConnectionState.waiting) {
              return Center(
                child: CircularProgressIndicator(),
              );
            } else if (snapshot.data == null) {
              return Column(
                children: [Text("data null")],
              );
            } else {
              return Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Expanded(
                      child: Padding(
                    padding: const EdgeInsets.symmetric(
                        horizontal: kDefaultPaddin, vertical: 20),
                    child: GridView.builder(
                      
                      itemCount: snapshot.data.length,
                      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                          crossAxisCount: 2,
                          mainAxisSpacing: kDefaultPaddin,
                          crossAxisSpacing: kDefaultPaddin,
                          childAspectRatio: 0.55),
                      itemBuilder: (context, index) => itemBuku(
                          id: 1,
                          // title: null,
                          title: snapshot.data[index].title,
                          cover: snapshot.data[index].cover,
                          date: snapshot.data[index].rl_date,
                          press: () => Navigator.push(
                                context,
                                MaterialPageRoute(
                                    builder: (context) => DetailsScreen(
                                          product: snapshot.data[index],
                                        )),
                              )),
                    ),
                  ))
                ],
              );
            }
          },
        ));
  }
}

class itemBuku extends StatelessWidget {
  final String title;
  final String date;
  final String cover;
  final Function press;
  final int id;
  const itemBuku({
    Key key,
    this.title,
    this.date,
    this.id,
    this.cover,
    this.press,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: press,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Expanded(
            child: Container(
              padding: EdgeInsets.all(kDefaultPaddin),
              height: 230,
              width: 169,
              decoration: BoxDecoration(
                // color: product.color,
                borderRadius: BorderRadius.circular(16),
                image: DecorationImage(
                    // fit: BoxFit.fill, image: NetworkImage(cover)),
                    fit: BoxFit.fill,
                    image: NetworkImage(cover)),
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.symmetric(vertical: kDefaultPaddin / 4),
            child: Text(
              title,
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Text(date,
              // style: TextStyle(),
              style: Theme.of(context).textTheme.caption)
        ],
      ),
    );
  }
}

我使用了 easy list view 包。这将帮助您使用延迟加载程序 或者,如果您自己想要它,请按照此 this blog or geeksforgeeks blog