0
votes

I have created Flutter home page with BottomNavigationBar by following this link https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html

It is working fine. But I wanted to know how to go to the first page from the third page. I mean, inside the third page, I have a button, when the user clicks on it, I have to redirect the user to the first page. ( I'm not speaking about the button on the bottom navigation bar )

Is it possible?

1

1 Answers

0
votes

Just change the _selectedIndex and call the setState method,like this:

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,
        ),
      ),
    );
  }
}