Flutter解决TabBar顶部页面切换导致页面重载问题

问题描述

写蓝牙程序时,使用到了顶部Tab的切换,但是切换过程中读取到的内容会被重置。影响体验。

解决方法

看的该博主的方法

借鉴博主链接

1、保证自己使用的是动态的StatefulWidget
2、状态继承AutomaticKeepAliveClientMixin
3、重写get wantKeepAlive方法,并返回true

代码展示

1、父页面代码展示

csharp 复制代码
import 'package:flutter/material.dart';
import 'package:tabbarsaveinfo/tabs/mypage1.dart';
import 'package:tabbarsaveinfo/tabs/mypage2.dart';

import 'mypage3.dart';

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key});

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //appBar: AppBar(),
      body: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            title: Text("tabs Demo"),
            bottom: const TabBar(tabs: [
              Tab(
                text: "page1",
              ),
              Tab(
                text: "page2",
              ),
              Tab(
                text: "page3",
              ),
            ]),
          ),
          body: TabBarView(children: [
            MyPage1(),
            MyPage2(),
            MyPage3(),
          ]),
        ),
      ),
    );
  }
}

2、子页面代码展示

csharp 复制代码
import 'package:flutter/material.dart';

class MyPage1 extends StatefulWidget {
  const MyPage1({super.key});

  @override
  State<MyPage1> createState() => _MyPage1State();
}

class _MyPage1State extends State<MyPage1> with AutomaticKeepAliveClientMixin {
  TextEditingController _controller = TextEditingController();
  @override
  bool get wantKeepAlive => true;
  void add() {
    setState(() {
      _controller.text = 10.toString();
    });
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
          child: Column(
        children: [
          Center(
            child: Text("第1页面的内容"),
          ),
          TextField(
            controller: _controller,
          ),
          ElevatedButton(
              onPressed: () {
                add();
              },
              child: Text("按钮1"))
        ],
      )),
    );
  }
}

添加内容圈出来了

每一个tab页面都需要加上这些内容,有几个页面加几个。

相关推荐
书弋江山19 分钟前
flutter 跨平台编码库 protobuf 工具使用
android·flutter
程序员老刘·20 分钟前
Flutter 3.35 更新要点解析
flutter·ai编程·跨平台开发·客户端开发
tangweiguo0305198721 分钟前
Flutter vs Android:页面生命周期对比详解
flutter
tangweiguo0305198725 分钟前
Flutter网络请求实战:Retrofit+Dio完美解决方案
flutter
烛阴1 小时前
精简之道:TypeScript 参数属性 (Parameter Properties) 详解
前端·javascript·typescript
开发者小天2 小时前
为什么 /deep/ 现在不推荐使用?
前端·javascript·node.js
来来走走3 小时前
Flutter开发 webview_flutter的基本使用
android·flutter
Jerry说前后端3 小时前
Android 组件封装实践:从解耦到架构演进
android·前端·架构
找不到工作的菜鸟4 小时前
Three.js三大组件:场景(Scene)、相机(Camera)、渲染器(Renderer)
前端·javascript·html
定栓4 小时前
vue3入门-v-model、ref和reactive讲解
前端·javascript·vue.js