デフォルトでは、Flutter の PageView と TabBarView は、ページを切り替えるたびにページを再構築します。最新の UI がレンダリングされますが、この動作は、特にページに複雑なレイアウトとデータの読み込みがある場合にパフォーマンスの問題を引き起こす可能性があります。
この問題を解決するには、AutomaticKeepAliveClientMixin インターフェイスとその wantKeepAlive メソッドを使用できます。ページの状態を維持して、切り替えるたびに再構築が行われないようにします。
main.dart コード
import 'package:flutter/material.dart';
import 'package:tab_pageview/tab_pageview.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'TabPageView',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const TabPage(title: 'TabPageView'),
);
}
}
class TabPage extends StatefulWidget {
const TabPage({super.key, required this.title});
final String title;
@override
State<TabPage> createState() => _TabPageState();
}
class _TabPageState extends State<TabPage> {
static const tabs = ['全部', 'Android', 'Flutter', 'RN', 'Kotlin', 'IOS'];
get _tabPages => tabs.map((e) => TabPageView(tabName: e)).toList();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: PageView(
children: _tabPages,
),
);
}
}
tab_pageview.dart コード
import 'package:flutter/material.dart';
///PageView
class TabPageView extends StatefulWidget {
final String tabName;
const TabPageView({super.key, required this.tabName});
@override
State<TabPageView> createState() => _TabPageViewState();
}
class _TabPageViewState extends State<TabPageView>
with AutomaticKeepAliveClientMixin {
@override
Widget build(BuildContext context) {
super.build(context); //不要忘记加
debugPrint("TabPageView:build ${widget.tabName}");
return Center(
child: Text(
widget.tabName,
style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
);
}
@override
bool get wantKeepAlive => true; //返回true
}
ソースコードアドレス: GitHub - IBraveBegins/tab_pageview: タブでページを切り替えるときに頻繁に発生するビルドの問題