返回按钮将指向第一页



我使用一个DefaultTabController选项卡,它看起来像这个

class MainTabs extends StatelessWidget {
@override
Widget build(BuildContext context) {
return DefaultTabController(
length: 3,
child: Scaffold(
appBar: MyAppbar(),
body: TabBarView(
children: [
CardContentPage(title: 'Tab1'),
DeviceContentPage(title: 'Tab2'),
SettingsPage(title: 'Tab2'),
],
),
),
);
}
}

但在这种设计中,后退按钮总是指向应用程序的第一页。

如何设置它,使返回按钮与DefaultTabController一起按预期工作?

使用DefaultTabController,您可以使用WillPopScope:阻止用户返回

DefaultTabController(
initialIndex: 0,
length: 3,
child: WillPopScope(
onWillPop: () async {
return false;
},
child: Scaffold(
appBar: AppBar(
bottom: TabBar(tabs: [
Tab(text: 'First',),
Tab(text: 'Second',),
Tab(text: 'Third',),
]),
),
body: TabBarView(
children: [
Container(color: Colors.red,),
Container(color: Colors.yellow,),
Container(color: Colors.green,),
],
),
),
),
);

但使用TabController,您可以设置到上一页的路线:

class TabPage extends StatefulWidget {
@override
_TabPageState createState() => _TabPageState();
}
class _TabPageState extends State<TabPage> with SingleTickerProviderStateMixin {
TabController tabController;
@override
void initState() {
tabController = TabController(length: 3, vsync: this);
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
bottom: TabBar(
controller: tabController,
tabs: [
Tab(
text: 'First',
),
Tab(
text: 'Second',
),
Tab(
text: 'Third',
),
],
),
),
body: TabBarView(
controller: tabController,
children: [
Container(
color: Colors.red,
),
WillPopScope(
onWillPop: () async {
tabController.animateTo(0, duration: Duration(milliseconds: 500),);
return false;
},
child: Container(
color: Colors.yellow,
),
),
WillPopScope(
onWillPop: ()async {
tabController.animateTo(1, duration: Duration(milliseconds: 500),);
return false;
},
child: Container(
color: Colors.green,
),
),
],
),
);
}
}

相关内容

最新更新