Flutter PageView 子控件重复初始化解决方案
在使用 PageView 的过程中,或 bottomNavigationBar 关联使用时,会出现重复初始化子控件的现象,根据使用场景的不同,我们或许需要子控件只初始化一次,而不是重复初始化,改如何解决呢?
解决方法如下
page 页面添加 with AutomaticKeepAliveClientMixin 代码并复写方法即可
@override
bool get wantKeepAlive => true;
Page 页面完整代码如下
import 'package:flutter/material.dart';
class SearchPage extends StatefulWidget {
@override
createState() => SearchPageState();
}
class SearchPageState extends State<SearchPage> with AutomaticKeepAliveClientMixin{
@override
void initState() {
super.initState();
//注意看日志的打印
print("SearchPageInit");
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('搜索'),
centerTitle: true,
),
body: new Center(child: new Text('搜索')),
);
}
@override
bool get wantKeepAlive => true;
}
官方文档释义
/// A mixin with convenience methods for clients of [AutomaticKeepAlive]. Used
/// with [State] subclasses.
///
/// Subclasses must implement [wantKeepAlive], and their [build] methods must
/// call `super.build` (the return value will always return null, and should be
/// ignored).
///
/// Then, whenever [wantKeepAlive]'s value changes (or might change), the
/// subclass should call [updateKeepAlive].
///
/// The type argument `T` is the type of the [StatefulWidget] subclass of the
/// [State] into which this class is being mixed.
///
/// See also:
///
/// * [AutomaticKeepAlive], which listens to messages from this mixin.
/// * [KeepAliveNotification], the notifications sent by this mixin.