A scrollable list that works page by page.
Each child of a page view is forced to be the same size as the viewport.
You can use a PageController to control which page is visible in the view. In addition to being able to control the pixel offset of the content inside the PageView, a PageController also lets you control the offset in terms of pages, which are increments of the viewport size.
The PageController can also be used to control the PageController.initialPage, which determines which page is shown when the PageView is first constructed, and the PageController.viewportFraction, which determines the size of the pages as a fraction of the viewport size.
class ExPageView extends StatelessWidget {
const ExPageView({super.key});
@override
Widget build(BuildContext context) {
final PageController controller = PageController();
return PageView.builder(
controller: controller,
itemCount: 4,
// scrollDirection: Axis.vertical,
itemBuilder: (context, index) => Container(
color: Color(Random().nextInt(0xffffff)).withOpacity(0.4),
alignment: Alignment.center,
child: Text(
"Page $index",
style: TextStyle(fontSize: 36),
),
),
);
}
}Keep Alive1
A cache util class:
class KeepAliveWrapper extends StatefulWidget {
const KeepAliveWrapper({
Key? key,
this.keepAlive = true,
required this.child,
}) : super(key: key);
final bool keepAlive;
final Widget child;
@override
_KeepAliveWrapperState createState() => _KeepAliveWrapperState();
}
class _KeepAliveWrapperState extends State<KeepAliveWrapper>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context);
return widget.child;
}
@override
void didUpdateWidget(covariant KeepAliveWrapper oldWidget) {
if(oldWidget.keepAlive != widget.keepAlive) {
// keepAlive 状态需要更新,实现在 AutomaticKeepAliveClientMixin 中
updateKeepAlive();
}
super.didUpdateWidget(oldWidget);
}
@override
bool get wantKeepAlive => widget.keepAlive;
}Cached page:
PageView.builder(
itemCount: 4,
// scrollDirection: Axis.vertical,
itemBuilder: (context, index) => index & 1 == 1
? Container(
color: Color(Random().nextInt(0xffffff)).withOpacity(0.4),
alignment: Alignment.center,
child: Text(
"Page $index",
style: TextStyle(fontSize: 36),
),
)
: KeepAliveWrapper(
child: Container(
color: Color(Random().nextInt(0xffffff)).withOpacity(0.4),
alignment: Alignment.center,
child: Text(
"Page $index",
style: TextStyle(fontSize: 36),
),
),
),
)