0

I need to implement Pagination in flutter as list of products is very high. I need to make paginate with 20 items show at once. I tried below plugin, but that solution is not working. I have pasted my code without pagination which works fine with only issue when product list is high, it slows down page load time. is there any other other solution for pagination in flutter. I am using Laravel as backend.

plugin used : https://pub.dev/packages/flutter_paginator api: https://androidapp.factory2homes.com/api/get-products-for-mobile-case/26

class ProductByPhoneModel extends StatefulWidget {
  final phoneModel;
  ProductByPhoneModel(this.phoneModel);

  List<String> prod = new List();

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

class _ProductByPhoneModelState extends State<ProductByPhoneModel> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('f2h'),
      ),
      body: FutureBuilder<List<Product>>(
        future: getProductByPhoneModel(http.Client(), this.widget.phoneModel),
        builder: (context, snapshot) {
          if (snapshot.hasError) print(snapshot.error);
          return snapshot.hasData
              ? ProductByPhoneModelGrid(
                  product: snapshot.data,
                )
              : Center(
                  child: Center(
                      child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: <Widget>[
                      CircularProgressIndicator(),
                      Container(
                        height: 15,
                        width: double.infinity,
                      ),
                      Text('Factory2Homes'),
                    ],
                  )),
                );
        },
      ),
    );
  }
}

class ProductByPhoneModelGrid extends StatelessWidget {

  final List<Product> product;
  ProductByPhoneModelGrid({this.product});

  @override
  Widget build(BuildContext context) {
    return GridView.builder(
        shrinkWrap: true,

        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2,
          childAspectRatio: 3 / 4,
        ),
        itemCount: product.length,
        scrollDirection: Axis.vertical,
        itemBuilder: (context, index) {
          return InkWell(
         //   onTap: () async {
         //     Navigator.pushNamed(context, '/ProductDetailLandingPage',arguments: product[index]);
         //     SharedPreferences prefs = await SharedPreferences.getInstance();
         //     createProductPageVisit(prefs.getInt('userId'), 'ProductByCategory', product[index].productId, prefs.getString('token'));
         //   },
            child: Card(
              child: Column(
                children: <Widget>[
                  Container(
                      height: 150,
                      width: double.maxFinite,
                      child: Image.network(
                        product[index].productPhoto,
                        fit: BoxFit.fill,
                      )),
                  Center(
                    child: Text(product[index].productName, overflow: TextOverflow.ellipsis,
                        maxLines: 3,
                        style: TextStyle(
                          fontSize: 12,
                        )
                    ),
                  ),
                  Center(
                    child: RichText(
                        text: TextSpan(
                            style: DefaultTextStyle.of(context).style,
                            children: [
                              TextSpan(

                                  text:
                                  '\u20B9 ${product[index].productSalePrice}'),
                              TextSpan(
                                  text:
                                  ' ${product[index].productListPrice}',
                                  style: TextStyle(
                                      fontSize: 12,
                                      decoration: TextDecoration.lineThrough,
                                      color: Colors.grey)),
                            ])),
                  ),
                  Center(
                    child: Text(((1 -
                        product[index].productSalePrice /
                            product[index]
                                .productListPrice) *
                        100)
                        .toStringAsFixed(0) +
                        '% Off', style: TextStyle(color: Colors.green),),
                  )
                ],
              ),
            ),
          );
        });
  }
}

1 Answer 1

2

I have not used that package, but if you just want to solve this problem you can look at this simple code github, you can make your own without using any package.

this is code

import 'package:flutter/material.dart';
import 'dart:async';
import 'dart:convert';
import 'package:http/http.dart' as http;
import 'package:scroll/server.dart';

class FutureStream extends StatefulWidget {
  FutureStream({Key key}) : super(key: key);
  final String name = 'zaid salah';
  @override
  _FutureStreamState createState() => _FutureStreamState();
}

class _FutureStreamState extends State<FutureStream> {
  var uri = '${Server.domain}/web/vuecrud/public/test';
  var nexturl;
  ScrollController _scrollController = new ScrollController();
  List<Test> tempList = [];
  //determine if all data has been recieved
  var loadCompleted = false;

  Future<List<Test>> getData(uri) async {
    final response = await http.get(uri);
    if (response.statusCode == 200) {
      var testJson = json.decode(response.body);
      var data = testJson['data'];
      if (testJson['next_page_url'] != null) {
        nexturl = testJson['next_page_url'];
      } else {
        loadCompleted = true;
      }
      for (var item in data) {
        Test test =
            new Test(item["id"], item["name"], item["email"], item["password"]);
        tempList.add(test);
      }
      return tempList;
    } else {
      throw Exception('Failed to load Test');
    }
  }

  Future<List<Test>> data;
  @override
  void initState() {
    data = getData(uri);
    scrollindecator();
    super.initState();
  }

  void scrollindecator() {
    _scrollController.addListener(
      () {
        if (_scrollController.offset >=
                _scrollController.position.maxScrollExtent &&
            !_scrollController.position.outOfRange) {
          print('reach to bottom botton');
          if (!loadCompleted) {
            setState(() {
              //add more data to list
              data = getData(nexturl);
            });
          }
        }
      },
    );
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    print("app called again");
    return Scaffold(
      appBar: AppBar(
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.search),
            onPressed: () {},
          ),
        ],
        centerTitle: true,
        title: Text("stream vs future"),
      ),
      body: SingleChildScrollView(
        controller: _scrollController,
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: <Widget>[
            FutureBuilder(
              future: data,
              builder: (BuildContext context, AsyncSnapshot snapshot) {
                if (!snapshot.hasData) {
                  return Container(
                    child: Center(
                      child: CircularProgressIndicator(),
                    ),
                  );
                } else {
                  //if (snapshot.connectionState == ConnectionState.done) {
                  return ListView.builder(
                      physics: ScrollPhysics(),
                      shrinkWrap: true,
                      itemCount: snapshot.data.length ?? 0,
                      itemBuilder: (BuildContext contex, int index) {
                        if (index == snapshot.data.length - 1 &&
                            !loadCompleted) {
                          return Center(
                            child: new Opacity(
                              opacity: 1.0,
                              child: new CircularProgressIndicator(),
                            ),
                          );
                        } else {
                          return ListTile(
                            leading: CircleAvatar(
                                backgroundColor: Colors.white,
                                child:
                                    Text(snapshot.data[index].id.toString())),
                            title: Text(snapshot.data[index].name),
                            subtitle: Text(snapshot.data[index].email),
                            trailing: Icon(
                              Icons.info,
                              color: Colors.blue,
                            ),
                            onTap: () {
                              print(index);
                            },
                          );
                        }
                      }
                      //  },
                      );
                }
              },
            ),
          ],
        ),
      ),
    );
  }
}

class Test {
  final int id;
  final String name;
  final String email;
  final String password;
  Test(this.id, this.name, this.email, this.password);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.