如何在Flutter中的BottomNavigationBar中使用命名路线?

问题描述

我正在使用BottomNavigationBar,并且单击导航栏中的任何图标。我希望它进入下一个屏幕。这就是为什么我在这里使用命名路由的原因。

main.dart代码


import 'package:Flutter/material.dart';

import 'Screens/profilePage1/profilePage1.dart';


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

class MyStatefulWidget extends StatefulWidget {
  @override
  _MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
  int _selectedindex = 0;



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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
            routes: {
        // When navigating to the "/" route,build the FirstScreen widget.
        '/first': (context) => ProfilePage1(),// When navigating to the "/second" route,build the SecondScreen widget.
        '/second': (context) => ProfilePage1(),'/third': (context) => ProfilePage1(),'/fourth': (context) => ProfilePage1(),'/fifth': (context) => ProfilePage1(),},home: Scaffold(
        
        body: Center(
          child: routes.elementAt(_selectedindex),),bottomNavigationBar: BottomNavigationBar(
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(icon: Icon(Icons.home),title: Text("")),BottomNavigationBarItem(
                icon: Icon(Icons.calendar_today),BottomNavigationBarItem(
                icon: Icon(
                  Icons.account_circle,size: 35,color: Color(0xFF334192),BottomNavigationBarItem(icon: Icon(Icons.message),BottomNavigationBarItem(
                icon: Icon(Icons.table_chart),],currentIndex: _selectedindex,selectedItemColor: Color(0xFF334192),unselectedItemColor: Colors.grey,onTap: (index){

          },);
  }
}

在这里,我创建了5条命名路线。我希望它在单击特定选项卡时传递到正文。我该怎么办?

解决方法

使用 Navigator.pushNamed()

onTap: (index){
  switch(index){
      case 0:
        Navigator.pushNamed(context,"/first");
        break;
      case 1:
        Navigator.pushNamed(context,"/second");
        break;
        ...etc
    }
 },

Navigator.pushedName()需要上下文来找到包含导航器路由的 Ancestor 小部件,现在您的BottomNavigationBar已经在Root Widget- MaterialApp ,它不是BottomNavigationBar的祖先,而是在同一上下文中。

,

只需使用Navigator的pushNamed方法 Navigator.pushNamed(context,'Name'); Header Manager

 onTap: (index){
   switch (index) {
     case 0:
       Navigator.pushNamed(context,'/first');
     break;
     case 2:
       Navigator.pushNamed(context,'/second');
     break;
 },