Steps to reproduce: Swipe to the left, switch to the red Tab
and then switch to the purple Tab
again.
What is: After executing the steps to reproduce, the PageView
of the first Tab
is at the blue page again.
What should be: After executing the steps to reproduce, the PageView
of the first Tab
is still at the green page.
What am I missing here?
import "package:flutter/material.dart";
import "package:flutter/services.dart";
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
SystemChrome.setEnabledSystemUIOverlays([]);
return MaterialApp(
home: MyHome()
);
}
}
class MyHomeState extends State<MyHome> with TickerProviderStateMixin {
TabController tabController;
@override
void initState() {
tabController = tabController?? TabController(
vsync: this,
length: 2
);
super.initState();
}
@override
void dispose() {
tabController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
children: [
TabBar(
controller: tabController,
tabs: [
Container(
color: Colors.purple,
width: 100.0,
height: 50.0
),
Container(
color: Colors.pink,
width: 100.0,
height: 50.0
)
]
),
Expanded(
child: TabBarView(
controller: tabController,
children: [
MyPageView(),
MyPageView(),
],
)
)
]
)
);
}
}
class MyHome extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyHomeState();
}
}
class MyPageViewState extends State<MyPageView> {
PageController pageController;
@override
void initState() {
pageController = pageController?? PageController();
super.initState();
}
@override
void dispose() {
pageController.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return PageView(
controller: pageController,
children: [
Container(
color: Colors.blue
),
Container(
color: Colors.green
)
]
);
}
}
class MyPageView extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return MyPageViewState();
}
}
PageController is used to control the PageView . That's include which page should be shown first, how each page should occupy the viewport, as well as whether to keep the page number when the scrollable is recreated.
This is problem is solved with AutomaticKeepAliveMixin
. I used this before, but due to confusion on the wrong state. It obviously has to be mixed in with the class that contains the state you want to keep alive
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With