如何从另一个statefullwidget的按钮单击中切换BottomNavigationBar?

时间:2019-07-10 14:20:48

标签: flutter dart flutter-layout flutter-dependencies

我在整个应用程序中都使用BottomNavigationBar从一个选项卡导航到另一个选项卡。 我将使用不同的statefullwidget。但是我可以通过调用setState自动导航。反正有做到这一点。下面我附有相同的代码。请给我一个建议

上一个我完成的应用没有导航。之后,我需要将导航添加到现有应用。但是面对这个问题。为了清楚地了解我的问题,我在下面提供了示例代码

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "MyHomePage",
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

int currentselected = 0;

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    List<Widget> _widgetOptions = <Widget>[
      Tabswitch(),
      Center(
        child: Container(
          child: RaisedButton(
            onPressed: () {
              setState(() {
                currentselected = currentselected == 0 ? 1 : 0;
              });
            },
            child: Text('Back'),
          ),
        ),
      ),
    ];
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(currentselected),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: [
          BottomNavigationBarItem(
              icon: Icon(Icons.ac_unit), title: Text('Name')),
          BottomNavigationBarItem(
              icon: Icon(Icons.access_time), title: Text('Name2')),
        ],
        currentIndex: currentselected,
        onTap: (index) {
          setState(() {
            currentselected = currentselected == 0 ? 1 : 0;
          });
        },
      ),
    );
  }
}

class Tabswitch extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return TabswitchState();
  }
}

class TabswitchState extends State<Tabswitch> {
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Center(
      child: Container(
        child: RaisedButton(
          onPressed: () {
            setState(() {
              currentselected = currentselected == 0 ? 1 : 0;
            });
          },
          child: Text('Next'),
        ),
      ),
    );
  }
}

当设置为Setstate时,currentselected值将更新,但不会自动导航到currentselected选项卡。

0 个答案:

没有答案