如何从另一个页面访问tabbarcontroller?

时间:2019-09-08 11:14:49

标签: flutter navigation tabbar

我想从另一个页面访问tabbarview。这样我就可以通过单击按钮立即访问第三个tabbarview。无需转到第一页。这怎么可能?

IconButton(
  onPressed: () {
    Navigator.push(
      context,
      MaterialPageRoute(
          builder: (context) => firstpage()), // here i want immediately go to third page
    );
  },
);

当我将第三页作为MaterialPageRout插入时,我的应用程序和标签栏丢失了。

class Home extends StatefulWidget {
Home({Key key, this.title}) : super(key: key);



final int title;
@override
State<StatefulWidget> createState() {
return HomeExtended();
 }

}

class HomeExtended extends State<Home> with TickerProviderStateMixin {

//here I want to acces the title from home 
// when I add super(key: key) it marks the key
// I think its because it is not a stateful widget

1 个答案:

答案 0 :(得分:1)

假设我们有以下应用程序:

import 'package:flutter/material.dart';

void main() {
  runApp(TabBarDemo());
}

class TabBarDemo extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: DefaultTabController(
        length: 3,
        child: Scaffold(
          appBar: AppBar(
            bottom: TabBar(
              tabs: [
                Tab(icon: Icon(Icons.directions_car)),
                Tab(icon: Icon(Icons.directions_transit)),
                Tab(icon: Icon(Icons.directions_bike)),
              ],
            ),
            title: Text('Tabs Demo'),
          ),
          body: TabBarView(
            children: [
              Icon(Icons.directions_car),
              Icon(Icons.directions_transit),
              Icon(Icons.directions_bike),
            ],
          ),
        ),
      ),
    );
  }
}

将以下内容添加到TabBarDemo

final int initialIndex;
TabBarDemo({Key key, this.initialIndex}) : super(key: key);

DefaultTabController修改为:

//...
DefaultTabController(
     length: 3,
     initialIndex: initialIndex??0,
//...

然后,当路由到TabBarDemo类时,您可以这样称呼它:

Navigator.push(
  context,
  MaterialPageRoute(
      builder: (context) => TabBarDemo(initialIndex:2)),
);

编辑: 如果您使用的是StatefulWidget,并且其状态是扩展了State的另一个类,则在状态类中,您可以通过关键字widget访问有状态窗口小部件。

initialIndex: widget.initialIndex??0,