(我是 Flutter 的新手)我正在尝试在我的项目中实现分页。我是否正在使用 GridView 来使用提供程序显示我的项目。我面临的问题是,当我滚动提要时,页面上会加载新项目,而不会加载之前调用的所有项目。(例如,如果我有 12 个项目列表并且屏幕上显示了 4 个项目,并且如果我尝试滚动查看所有其他项目,则会进行新调用,并且新产品会从 api 调用加载到屏幕上)。滚动也无法在 android 设备上运行。
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/products.dart';
import '../widgets/product_card.dart';
class ProductsGrid extends StatefulWidget {
@override
_ProductsGridState createState() => _ProductsGridState();
}
class _ProductsGridState extends State<ProductsGrid> {
ScrollController _scrollController;
var _isInit = true;
int _pageId = 1;
@override
void didChangeDependencies() {
if (_isInit) {
Provider.of<Products>(context).getHomepageProducts(_pageId);
}
_isInit = false;
super.didChangeDependencies();
}
@override
void initState() {
_scrollController = new ScrollController();
_scrollController.addListener(() {
// print(_scrollController.position.pixels);
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent &&
!_scrollController.position.outOfRange) {
_fetchForward(++_pageId);
print(_pageId);
} else if (_scrollController.position.pixels ==
_scrollController.position.minScrollExtent &&
_pageId > 1 &&
!_scrollController.position.outOfRange) {
_fetchBackward(--_pageId);
}
});
super.initState();
}
_fetchBackward(_pageId) async {
Provider.of<Products>(context).getHomepageProducts(_pageId);
setState(() {});
}
_fetchForward(_pageId) async {
Provider.of<Products>(context, listen: false).getHomepageProducts(_pageId);
setState(() {});
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
final productsData = Provider.of<Products>(context, listen: false);
final products = productsData.items;
return (products.isNotEmpty)
? Container(
child: GridView.builder(
controller: _scrollController,
itemCount: products.length,
shrinkWrap: true,
// reverse: true,
physics: const AlwaysScrollableScrollPhysics(),
gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
childAspectRatio: 3 / 5,
crossAxisSpacing: 5.0,
mainAxisSpacing: 5.0,
),
itemBuilder: (ctx, i) => ChangeNotifierProvider.value(
value: products[i], child: ProductCard()),
),
)
: Container(
child: Column(
children: [
Padding(
padding: const EdgeInsets.only(top: 350),
child: Center(
child: CircularProgressIndicator(),
),
),
Padding(
padding: const EdgeInsets.only(top: 10),
child: Text(
"Loading...",
style: TextStyle(fontSize: 25),
),
),
],
),
);
}
}