Skip to content

Instantly share code, notes, and snippets.

@Sunbreak
Created March 10, 2022 10:09
Show Gist options
  • Save Sunbreak/8d5c2fbb09ad2c531213f82a16b2bc9b to your computer and use it in GitHub Desktop.
Save Sunbreak/8d5c2fbb09ad2c531213f82a16b2bc9b to your computer and use it in GitHub Desktop.
Flutter-TabBarView-KeepAlive
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final indexes = List.generate(10, (index) => index);
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: indexes.length,
child: Scaffold(
appBar: AppBar(
title: Text(widget.title),
bottom: TabBar(
isScrollable: true,
tabs: [
for (var i in indexes)
Tab(text: 'tab$i'),
],
),
),
body: TabBarView(
children: [
...indexes.map((i) {
return i % 2 == 0 ? PlainWidget(i: i) : AliveWidget(i: i);
})
],
),
),
);
}
}
class PlainWidget extends StatelessWidget {
const PlainWidget({
Key? key,
required this.i,
}) : super(key: key);
final int i;
@override
Widget build(BuildContext context) {
debugPrint('PlainWidget build $i');
return Center(
child: Text('PlainWidget$i'),
);
}
}
class AliveWidget extends StatefulWidget {
const AliveWidget({
Key? key,
required this.i,
}) : super(key: key);
final int i;
@override
State<StatefulWidget> createState() => AliveWidgetState();
}
class AliveWidgetState extends State<AliveWidget> with AutomaticKeepAliveClientMixin {
@override
bool get wantKeepAlive => true;
@override
Widget build(BuildContext context) {
super.build(context);
debugPrint('AliveWidget build ${widget.i}');
return Center(
child: Text('AliveWidget${widget.i}'),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment