在使用BottomNavigationBar加载的页面之间切换切换

时间:2020-03-19 08:29:23

标签: flutter

通过点击此链接https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html,我已经使用BottomNavigationBar创建了Flutter主页。

工作正常。但是我想知道如何从第三页转到第一页。我的意思是,在第三页中,我有一个按钮,当用户单击它时,我必须将用户重定向到第一页。 (我不是在说底部导航栏上的按钮)

有可能吗?

1 个答案:

答案 0 :(得分:0)

只需更改_selectedIndex并调用setState方法,如下所示:

class TestWidget extends StatefulWidget {
  @override
  _TestWidgetState createState() => _TestWidgetState();
}

class _TestWidgetState extends State<TestWidget>
    with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
      TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

  List<Widget> _widgetOptions;

  @override
  void initState() {
    super.initState();
    _widgetOptions = <Widget>[
      Text(
        'Index 0: Home',
        style: optionStyle,
      ),
      Text(
        'Index 1: Business',
        style: optionStyle,
      ),
      TestBusinessPage<Object>((data,index){
        _onItemTapped(index);
      }),
    ];
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('BottomNavigationBar Sample'),
      ),
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text('Home'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            title: Text('Business'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            title: Text('School'),
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

/// T is business data,index is target index
typedef void OnButtonClicked<T>(T data, int index);

class TestBusinessPage<T> extends StatelessWidget {
  final OnButtonClicked buttonClicked;

  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);

  TestBusinessPage(this.buttonClicked);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: RaisedButton(
        onPressed: () {
          buttonClicked(null,0);
        },
        child: Text(
          'Index 2: School',
          style: optionStyle,
        ),
      ),
    );
  }
}