Flutter中如何跳转至DefaultTabController的指定标签页?
解决方案
要实现跳转至OrderList页面时直接展示第三个“Cancelled”标签页,通过传递初始标签索引并配置DefaultTabController的initialIndex属性即可实现,具体步骤如下:
1. 为OrderList添加初始索引参数
修改OrderList类,新增可选参数用于接收初始选中的标签索引,默认值设为0以兼容原有跳转逻辑:
class OrderList extends StatefulWidget { final int initialTabIndex; const OrderList({super.key, this.initialTabIndex = 0}); @override State<OrderList> createState() => _OrderListState(); }
2. 配置DefaultTabController的初始索引
在_OrderListState的build方法中,将DefaultTabController的initialIndex设置为传递过来的参数:
@override Widget build(BuildContext context) { return DefaultTabController( length: 3, initialIndex: widget.initialTabIndex, // 使用传入的初始索引 child: Container( // 原有代码保持不变 decoration: BoxDecoration( color: Colors.teal[300], ), child: Scaffold( bottomNavigationBar: BottomNavigationBarForAppClient(indexNum: 1), backgroundColor: Colors.transparent, appBar: AppBar( title: const Text('Order List'), centerTitle: true, flexibleSpace: Container( decoration: BoxDecoration( color: Colors.teal[300], ), ), ), body: Column( children: [ TabBar(tabs: [ Tab(text: 'In Progress'), Tab(text: 'Completed'), Tab(text: 'Cancelled'), ]), Expanded( child: TabBarView(children: [ ProgressClient(), CompletedClient(), CancelledClient(), ]), ) ], ), ), ), ); }
3. 跳转时指定目标标签索引
修改跳转代码,实例化OrderList时传入initialTabIndex: 2(标签索引从0开始,第三个“Cancelled”标签对应索引2):
IconButton( onPressed: () { Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => OrderList(initialTabIndex: 2))); }, icon: Icon(Icons.arrow_back, size: 40, color: Colors.white)),
修改完成后,点击该按钮跳转至OrderList页面时,会直接选中并展示“Cancelled”标签页,同时不影响其他场景下默认选中第一个标签的逻辑。
内容的提问来源于stack exchange,提问作者Hisywm
相关产品推荐
相关产品推荐

