如何使用底部导航栏导航到新页面?

How do i navigate to new pages using my bottom-navigation-bar?

我想使用底部导航栏导航到新页面。使用底部导航栏和我在下面附加的代码导航到新页面的可能方法有哪些。

此外,我不希望在我的新页面中使用底部导航栏。我只想要当前页面的底部导航栏。

提前致谢。

代码:

class dashboard extends StatefulWidget {
  @override
  _dashboardState createState() => _dashboardState();
}

// ignore: camel_case_types
class _dashboardState extends State<dashboard> {
  int currentIndex = 1;

  changeIndex(index) {
    setState(() {
      currentIndex = index;
    });
  }

  @override
  Widget build(BuildContext context) {
    final authService = Provider.of<AuthService>(context);
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 80.0, right: 250),
              child: Center(
                child: Container(
                  width: 200.0,
                  height: 20.0,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(15.0)),
                  child: (const Text(
                    'Hello',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.black),
                  )),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 300.0, top: 1.0),
              child: IconButton(
                icon: new Icon(Icons.account_circle, size: 30.0),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => Notifications(),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 300.0, top: 5.0),
              child: IconButton(
                icon: const Icon(
                  Icons.notifications,
                  size: 25.0,
                ),
                onPressed: () {
                  Navigator.push(
                    context,
                    MaterialPageRoute(
                      builder: (context) => Notifications(),
                    ),
                  );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 0.0),
              child: Center(
                child: Container(
                  width: 390,
                  height: 450,
                  decoration: BoxDecoration(
                      color: Colors.green.shade100,
                      borderRadius: BorderRadius.circular(10.0)),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () async {
        await authService.signOut();
      }),
      //  : _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.green[100],
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.book_online),
            label: 'Page 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.read_more),
            label: 'Page 2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle),
            label: 'Profile',
          ),
        ],
      ),
    );
  }
}

您可以在 BottomNavigationBar 上添加 onTap: onTabTapped,然后使用选定的索引导航到您的目标页面

  void onTabTapped(int index) {
    if(index==2) {
      Navigator.of(context).pushReplacement(
        new MaterialPageRoute(builder: (context) => new YourPage())
    }
  }

你可以使用onTap 属性

onTap: _onItemTapped,

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

查看完整代码

import 'package:flutter/material.dart';

class dashboadrState extends StatefulWidget {
  const dashboadrState({Key? key}) : super(key: key);

  @override
  State<dashboadrState> createState() => _dashboadrStateState();
}

class _dashboadrStateState extends State<dashboadrState> {
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  int _selectedIndex = 0;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 80.0, right: 250),
              child: Center(
                child: Container(
                  width: 200.0,
                  height: 20.0,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(15.0)),
                  child: (const Text(
                    'Hello',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.black),
                  )),
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 300.0, top: 1.0),
              child: IconButton(
                icon: new Icon(Icons.account_circle, size: 30.0),
                onPressed: () {
                  print("hit");
                  // Navigator.push(
                  //   context,
                  //   MaterialPageRoute(
                  //     builder: (context) => Notifications(),
                  //   ),
                  // );
                },
              ),
            ),
            Padding(
              padding: EdgeInsets.only(left: 300.0, top: 5.0),
              child: IconButton(
                icon: const Icon(
                  Icons.notifications,
                  size: 25.0,
                ),
                onPressed: () {
                  print("hit ");
                  // Navigator.push(
                  //   context,
                  //   MaterialPageRoute(
                  //     builder: (context) => Notifications(),
                  //   ),
                  // );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 0.0),
              child: Center(
                child: Container(
                  width: 390,
                  height: 450,
                  decoration: BoxDecoration(
                      color: Colors.green.shade100,
                      borderRadius: BorderRadius.circular(10.0)),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () async {
        // await authService.signOut();
      }),
      //  : _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.green[100],
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.book_online),
            label: 'Page 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.read_more),
            label: 'Page 2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

输出

更新答案(屏幕根据需要动态变化)

代码:-

import 'package:flutter/material.dart';

class dashboadrState extends StatefulWidget {
  const dashboadrState({Key? key}) : super(key: key);

  @override
  State<dashboadrState> createState() => _dashboadrStateState();
}

class _dashboadrStateState extends State<dashboadrState> {
  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  int _selectedIndex = 0;
  static final List<Widget> _widgetOptions = <Widget>[
    Scaffold(
      body: SingleChildScrollView(
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.only(top: 80.0, right: 250),
              child: Center(
                child: Container(
                  width: 200.0,
                  height: 20.0,
                  decoration:
                      BoxDecoration(borderRadius: BorderRadius.circular(15.0)),
                  child: (const Text(
                    'Hello',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                        fontWeight: FontWeight.bold, color: Colors.black),
                  )),
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 300.0, top: 1.0),
              child: IconButton(
                icon: const Icon(Icons.account_circle, size: 30.0),
                onPressed: () {
                  print("hit");
                  // Navigator.push(
                  //   context,
                  //   MaterialPageRoute(
                  //     builder: (context) => Notifications(),
                  //   ),
                  // );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(left: 300.0, top: 5.0),
              child: IconButton(
                icon: const Icon(
                  Icons.notifications,
                  size: 25.0,
                ),
                onPressed: () {
                  print("hit ");
                  // Navigator.push(
                  //   context,
                  //   MaterialPageRoute(
                  //     builder: (context) => Notifications(),
                  //   ),
                  // );
                },
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 0.0),
              child: Center(
                child: Container(
                  width: 390,
                  height: 450,
                  decoration: BoxDecoration(
                      color: Colors.green.shade100,
                      borderRadius: BorderRadius.circular(10.0)),
                ),
              ),
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(onPressed: () async {
        // await authService.signOut();
      }),
    ),
    const Text(
      'Index 1: Business',
    ),
    const Text(
      'Index 2: School',
    ),
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: _widgetOptions.elementAt(_selectedIndex),
      ),

      //  : _children[_currentIndex],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        backgroundColor: Colors.green[100],
        items: const [
          BottomNavigationBarItem(
            icon: Icon(Icons.book_online),
            label: 'Page 1',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.read_more),
            label: 'Page 2',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.account_circle),
            label: 'Profile',
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

输出

请参考以下代码

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
  int _currentTabIndex = 0;
  ValueNotifier<bool> refreshPage = ValueNotifier(false);

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      valueListenable: refreshPage,
      builder: (context, value, child) {
        return WillPopScope(
          onWillPop: () {
            Navigator.of(context).pop();
          },
          child: Scaffold(
            backgroundColor: _currentTabIndex == 0
                ? Colors.white
                : _currentTabIndex == 1
                    ? Colors.green
                    : Colors.green,
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              title: Text(
                "Bottom Navigation Bar",
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                    fontWeight: FontWeight.w600),
              ),
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  size: 18.0,
                  color: Colors.black,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              centerTitle: true,
            ),
            body: SingleChildScrollView(
              child: _currentTabIndex == 0
                  ? Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(top: 80.0, right: 250),
                          child: Center(
                            child: Container(
                              width: 200.0,
                              height: 20.0,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15.0)),
                              child: (const Text(
                                'Hello',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black),
                              )),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 300.0, top: 1.0),
                          child: IconButton(
                            icon: new Icon(Icons.account_circle, size: 30.0),
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Notifications(),
                                ),
                              );
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 300.0, top: 5.0),
                          child: IconButton(
                            icon: const Icon(
                              Icons.notifications,
                              size: 25.0,
                            ),
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Notifications(),
                                ),
                              );
                            },
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 0.0),
                          child: Center(
                            child: Container(
                              width: 390,
                              height: 450,
                              decoration: BoxDecoration(
                                  color: Colors.green.shade100,
                                  borderRadius: BorderRadius.circular(10.0)),
                            ),
                          ),
                        ),
                      ],
                    )
                  : _currentTabIndex == 1
                      ? Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                                color: Colors.green,
                                child: Center(child: Text("Page 2"))),
                          ],
                        )
                      : Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                                color: Colors.green,
                                child: Center(child: Text("Profile"))),
                          ],
                        ),
            ),
            bottomNavigationBar: _bottomNavigationBar(),
          ),
        );
      },
    );
  }

  Widget _bottomNavigationBar() {
    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.book_online),
          label: 'Page 1',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.read_more),
          label: 'Page 2',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.account_circle),
          label: 'Profile',
        )
      ],
      onTap: _onTap,
      currentIndex: _currentTabIndex,
    );
  }

  _onTap(int tabIndex) {
    switch (tabIndex) {
      case 0:
        Notifications();
        // _navigatorKey.currentState.pushReplacementNamed("Page 1");
        break;
      case 1:
        Notifications();
        //  _navigatorKey.currentState.pushReplacementNamed("Page 2");
        break;
      case 2:
        Notifications();
        // _navigatorKey.currentState.pushReplacementNamed("Profile");
        break;
    }

    _currentTabIndex = tabIndex;
    refreshPage.value = !refreshPage.value;
  }

  Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case "Page 1":
        return MaterialPageRoute(builder: (context) => Notifications()
            // Container(
            //     color: Colors.green, child: Center(child: Text("Page 1")))
            );
      case "Page 2":
        return MaterialPageRoute(builder: (context) => Notifications()
            //  Container(
            //     color: Colors.green, child: Center(child: Text("Page 2")))
            );
      default:
        return MaterialPageRoute(builder: (context) => Notifications()
            // Container(
            //     color: Colors.green, child: Center(child: Text("Profile")))
            );
    }
  }
}

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

  @override
  _NavitionState createState() => _NavitionState();
}

class _NavitionState extends State<Notifications> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.of(context).pop();
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            "Notification",
            style: TextStyle(
                color: Colors.black, fontSize: 14, fontWeight: FontWeight.w600),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 18.0,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          centerTitle: true,
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: Container(
                child: Text("Notification Body"),
              ),
            )
          ],
        ),
      ),
    );
  }
}

请参考以下代码:

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

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

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

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final GlobalKey<NavigatorState> _navigatorKey = GlobalKey<NavigatorState>();
  int _currentTabIndex = 0;
  ValueNotifier<bool> refreshPage = ValueNotifier(false);

  @override
  Widget build(BuildContext context) {
    return ValueListenableBuilder<bool>(
      valueListenable: refreshPage,
      builder: (context, value, child) {
        return WillPopScope(
          onWillPop: () {
            Navigator.of(context).pop();
          },
          child: Scaffold(
            backgroundColor: _currentTabIndex == 0
                ? Colors.white
                : _currentTabIndex == 1
                    ? Colors.green
                    : Colors.green,
            appBar: AppBar(
              backgroundColor: Colors.white,
              elevation: 0,
              title: Text(
                "Bottom Navigation Bar",
                style: TextStyle(
                    color: Colors.black,
                    fontSize: 14,
                    fontWeight: FontWeight.w600),
              ),
              leading: IconButton(
                icon: Icon(
                  Icons.arrow_back_ios,
                  size: 18.0,
                  color: Colors.black,
                ),
                onPressed: () {
                  Navigator.of(context).pop();
                },
              ),
              centerTitle: true,
            ),
            body: SingleChildScrollView(
              child: _currentTabIndex == 0
                  ? Column(
                      children: <Widget>[
                        Padding(
                          padding: const EdgeInsets.only(top: 80.0, right: 250),
                          child: Center(
                            child: Container(
                              width: 200.0,
                              height: 20.0,
                              decoration: BoxDecoration(
                                  borderRadius: BorderRadius.circular(15.0)),
                              child: (const Text(
                                'Hello',
                                textAlign: TextAlign.center,
                                style: TextStyle(
                                    fontWeight: FontWeight.bold,
                                    color: Colors.black),
                              )),
                            ),
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 300.0, top: 1.0),
                          child: IconButton(
                            icon: new Icon(Icons.account_circle, size: 30.0),
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Notifications(),
                                ),
                              );
                            },
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.only(left: 300.0, top: 5.0),
                          child: IconButton(
                            icon: const Icon(
                              Icons.notifications,
                              size: 25.0,
                            ),
                            onPressed: () {
                              Navigator.push(
                                context,
                                MaterialPageRoute(
                                  builder: (context) => Notifications(),
                                ),
                              );
                            },
                          ),
                        ),
                        Padding(
                          padding: const EdgeInsets.only(top: 0.0),
                          child: Center(
                            child: Container(
                              width: 390,
                              height: 450,
                              decoration: BoxDecoration(
                                  color: Colors.green.shade100,
                                  borderRadius: BorderRadius.circular(10.0)),
                            ),
                          ),
                        ),
                      ],
                    )
                  : _currentTabIndex == 1
                      ? Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                                color: Colors.green,
                                child: Center(child: Text("Page 2"))),
                          ],
                        )
                      : Column(
                          crossAxisAlignment: CrossAxisAlignment.center,
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Container(
                                color: Colors.green,
                                child: Center(child: Text("Profile"))),
                          ],
                        ),
            ),
            bottomNavigationBar: _bottomNavigationBar(),
          ),
        );
      },
    );
  }

  Widget _bottomNavigationBar() {
    return BottomNavigationBar(
      type: BottomNavigationBarType.fixed,
      items: [
        BottomNavigationBarItem(
          icon: Icon(Icons.book_online),
          label: 'Page 1',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.read_more),
          label: 'Page 2',
        ),
        BottomNavigationBarItem(
          icon: Icon(Icons.account_circle),
          label: 'Profile',
        )
      ],
      onTap: _onTap,
      currentIndex: _currentTabIndex,
    );
  }

  _onTap(int tabIndex) {
    switch (tabIndex) {
      case 0:
        Notifications();
        // _navigatorKey.currentState.pushReplacementNamed("Page 1");
        break;
      case 1:
        Notifications();
        //  _navigatorKey.currentState.pushReplacementNamed("Page 2");
        break;
      case 2:
        Notifications();
        // _navigatorKey.currentState.pushReplacementNamed("Profile");
        break;
    }

    _currentTabIndex = tabIndex;
    refreshPage.value = !refreshPage.value;
  }

  Route<dynamic> generateRoute(RouteSettings settings) {
    switch (settings.name) {
      case "Page 1":
        return MaterialPageRoute(builder: (context) => Notifications()
            // Container(
            //     color: Colors.green, child: Center(child: Text("Page 1")))
            );
      case "Page 2":
        return MaterialPageRoute(builder: (context) => Notifications()
            //  Container(
            //     color: Colors.green, child: Center(child: Text("Page 2")))
            );
      default:
        return MaterialPageRoute(builder: (context) => Notifications()
            // Container(
            //     color: Colors.green, child: Center(child: Text("Profile")))
            );
    }
  }
}

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

  @override
  _NavitionState createState() => _NavitionState();
}

class _NavitionState extends State<Notifications> {
  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () {
        Navigator.of(context).pop();
      },
      child: Scaffold(
        backgroundColor: Colors.white,
        appBar: AppBar(
          backgroundColor: Colors.white,
          elevation: 0,
          title: Text(
            "Notification",
            style: TextStyle(
                color: Colors.black, fontSize: 14, fontWeight: FontWeight.w600),
          ),
          leading: IconButton(
            icon: Icon(
              Icons.arrow_back_ios,
              size: 18.0,
              color: Colors.black,
            ),
            onPressed: () {
              Navigator.of(context).pop();
            },
          ),
          centerTitle: true,
        ),
        body: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Center(
              child: Container(
                child: Text("Notification Body"),
              ),
            )
          ],
        ),
      ),
    );
  }
}