flutter PageView重复初始化

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.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值