【问题标题】:I want to navigate with bottom navigation bar我想用底部导航栏导航
【发布时间】:2022-01-05 05:53:07
【问题描述】:

我有颤振应用程序,在我的应用程序中,我必须为每个页面显示底部导航栏

我很困惑我应该使用底部导航栏导航还是必须为每个页面添加底部导航栏

如果我使用导航,我必须使用脚手架作为所有小部件的父级,所以有什么方法可以使用脚手架导航。

这是我的代码:-


class WorkerHomeScreen extends StatelessWidget {
  WorkerHomeScreen({Key? key}) : super(key: key);
  int _selectedPageIndex = 0;

  List<Map<String, dynamic>> get _pages {
    return [
      {"page": SignInScreen(), "name": "PROPERTY", "action": null},
      {
        "page": ChoseRoleScreen(),
        "name": "CHAT",
        "action": ["Search"]
      },
      {"page": LandingPage(), "name": "VIDEO", "action": null},
      {"page": EmployerSignUpScreen(), "name": "PROFILE", "action": null}
    ];
  }

  void _selectPage(int index) {
    _selectedPageIndex = index;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        automaticallyImplyLeading: false,
      ),
      body: _pages[_selectedPageIndex]["page"],
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        onTap: _selectPage,
        currentIndex: _selectedPageIndex,
        items: [
          BottomNavigationBarItem(
            icon: Icon(workerNavigationLists[0].icon),
            label: "Property",
            activeIcon: Icon(workerNavigationLists[0].icon),
          ),
          BottomNavigationBarItem(
            icon: Icon(workerNavigationLists[1].icon),
            label: "Chat",
            activeIcon: Icon(workerNavigationLists[0].icon),
          ),
          BottomNavigationBarItem(
            icon: Icon(workerNavigationLists[0].icon),
            label: "Video",
          ),
          BottomNavigationBarItem(
            icon: Icon(workerNavigationLists[0].icon),
            label: "Profile",
            activeIcon: Icon(workerNavigationLists[0].icon),
          ),
        ],
      ),
    );
  }
}

这是我的屏幕:-

class SignInMobile extends StatelessWidget {
  SignInMobile({Key? key}) : super(key: key);
  final SignInController signInController = Get.find();
  @override
  Widget build(BuildContext context) {
    return Container(
      child: Center(
        child: RaisedButton(
          onPressed: () {
             /// I want to navigate to other page but I want navigation bar in other page also
               
             },
          child: Text("TAP TO NAVIGATE"),
        ),
      ),
    );
  }
}

【问题讨论】:

  • 感谢您的回复 Anmol,但我想使用底部导航栏导航,您的参考建议如何添加底部导航栏它完全不同的东西
  • 嗨,@DipakRamoliya 只是想问一下,你想保持底部导航不变,当你点击 navbatitem 时,你已经转到该选定项目本身的不同页面
  • 是的,我想要和你说的一样
  • 好吧,等一下,我会为你创建一个例子。并展示其中的工作

标签: flutter dart uinavigationbar


【解决方案1】:

所以从讨论中我创建了一个例子

查看以下链接以获取演示: https://github.com/sagaracharya24/bottomApp.git

因此,为了进行此实施,您必须了解以下内容

  1. OnGenerate 路由机制。
  2. GlobalKeys 和 NavigatorState。
  3. 了解 Offstage 小部件如何在后台工作。

您将从示例中得到什么:

  1. 每个页面都按照 BottomBarItem 维护页面堆栈。
  2. 如果您深入嵌套页面并单击同一项目,它将删除所有页面并返回主页面。

我还添加了示例 Gif 以向您展示该应用正在运行。

如果它对你有用,请告诉我。

【讨论】:

  • 我已经完成了您的实施,并且只需几个 twerk 就可以正常工作。任何愿意有上述相同行为的人都应该试试这个。谢谢
【解决方案2】:

您可以使用persistent_bottom_nav_bar 来实现您的期望。执行以下操作:

late PersistentTabController _controller;
 @override
void initState() {
    super.initState();
    _controller = PersistentTabController(initialIndex: 0);
   
  }
     List<PersistentBottomNavBarItem> _navBarsItems() {
    return [
      PersistentBottomNavBarItem(
        icon: Image.asset('assets/logowhite.png', height: 30, width: 30),
        inactiveIcon:
            Image.asset('assets/logowhite.png', height: 30, width: 30),
        title: "Vesvusa",
        textStyle: const TextStyle(color: Colors.white),
        activeColorPrimary: MyTheme.grey,
        activeColorSecondary: Colors.white,
        contentPadding: 5,
        inactiveColorPrimary: Colors.white,
        inactiveColorSecondary: Colors.white,
        routeAndNavigatorSettings: RouteAndNavigatorSettings(
          initialRoute: '/dashboard',
          routes: {
            '/newsevents': (context) => NewsListScreen(
                menuScreenContext: context,
                hideMainAppBar: hideMainAppBar,
                itemCount: null),
            '/blogdetails': (context) => BlogDetails(
                  menuScreenContext: context,
                  hideMainAppBar: hideMainAppBar,
                ),
            '/videoslist': (context) => VideosList(menuScreenContext: context),
            '/bookings': (context) => Bookings(menuScreenContext: context),
            '/lookstheme': (context) => LooksTheme(menuScreenContext: context),
            '/catalog': (context) => Catalog(menuScreenContext: context),
            '/productdetails': (context) =>
                ProductDetails(menuScreenContext: context),
          },
        ),
      ),
      PersistentBottomNavBarItem(
        icon: Image.asset(
          'assets/search.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        inactiveIcon: Image.asset(
          'assets/search.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        title: ("Search"),
        activeColorPrimary: MyTheme.grey,
        activeColorSecondary: Colors.white,
        contentPadding: 5,
        inactiveColorPrimary: Colors.white,
        inactiveColorSecondary: Colors.white,
        routeAndNavigatorSettings: const RouteAndNavigatorSettings(
          initialRoute: '/search',
          routes: {
//            '/first': (context) => MainScreen2(),
//            '/second': (context) => MainScreen3(),
          },
        ),
      ),
      PersistentBottomNavBarItem(
        icon: Image.asset(
          'assets/favourite.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        inactiveIcon: Image.asset(
          'assets/favourite.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        title: ("Favorite"),
        activeColorPrimary: MyTheme.grey,
        activeColorSecondary: Colors.white,
        contentPadding: 5,
        inactiveColorPrimary: Colors.white,
        inactiveColorSecondary: Colors.white,
        textStyle: const TextStyle(color: Colors.white),
        routeAndNavigatorSettings: const RouteAndNavigatorSettings(
          initialRoute: '/favorite',
          routes: {
//              '/first': (context) => MainScreen2(),
//              '/second': (context) => MainScreen3(),
          },
        ),
//          onPressed: (context) {
//            pushDynamicScreen(context,
//                screen: SampleModalScreen(), withNavBar: true);
//          }
      ),
      PersistentBottomNavBarItem(
        icon: Image.asset(
          'assets/cart.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        inactiveIcon: Image.asset(
          'assets/cart.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        title: ("Cart"),
        activeColorPrimary: MyTheme.grey,
        activeColorSecondary: Colors.white,
        contentPadding: 5,
        inactiveColorPrimary: Colors.white,
        inactiveColorSecondary: Colors.white,
        textStyle: const TextStyle(color: Colors.white),
        routeAndNavigatorSettings: const RouteAndNavigatorSettings(
          initialRoute: '/cart',
          routes: {
//            '/first': (context) => MainScreen2(),
//            '/second': (context) => MainScreen3(),
          },
        ),
      ),
      PersistentBottomNavBarItem(
        icon: Image.asset(
          'assets/profile.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        inactiveIcon: Image.asset(
          'assets/profile.png',
          height: 25,
          width: 25,
          color: Colors.white,
        ),
        title: ("Profile"),
        activeColorPrimary: MyTheme.grey,
        activeColorSecondary: Colors.white,
        contentPadding: 5,
        inactiveColorPrimary: Colors.white,
        inactiveColorSecondary: Colors.white,
        textStyle: const TextStyle(color: Colors.white),
        routeAndNavigatorSettings: RouteAndNavigatorSettings(
          initialRoute: '/profile',
          routes: {
            '/orders': (context) => MyOrders(
                  menuScreenContext: context,
                ),
            '/loginsecurity': (context) => LoginSecurity(
                  menuScreenContext: context,
                ),
            '/payment': (context) => Payment(
                  menuScreenContext: context,
                ),
            '/message': (context) => Messages(
                  menuScreenContext: context,
                ),
            '/devices': (context) => Devices(
                  menuScreenContext: context,
                ),
            '/devices': (context) => Devices(
                  menuScreenContext: context,
                ),
            '/inboxdetails': (context) => InboxDetails(
                  menuScreenContext: context,
                ),
            '/loyalty': (context) => Loyalty(menuScreenContext: context),
          },
        ),
      ),
    ];
  }

 @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: MyTheme.themeColor,
      appBar:  AppBar(
              elevation: 0,
              iconTheme: IconThemeData(
                color: MyTheme.grey,
              ),
              centerTitle: true,
              backgroundColor: MyTheme.themeColor,
              title: Image.asset("assets/titles.png", height: 60, width: 100),
              actions: [
                Builder(
                  builder: (context) {
                    return InkWell(
                        onTap: () {
                          Scaffold.of(context).openEndDrawer();
                        },
                        child: Padding(
                          padding: const EdgeInsets.fromLTRB(0, 0, 20, 0),
                          child: Icon(Icons.notifications_none_outlined,
                              color: MyTheme.grey),
                        ));
                  },
                )
              ],
            ),
      drawer: MyDrawer(),
      endDrawer: const NotificationDrawer(),
      body: PersistentTabView(
        context,
        controller: _controller,
        screens: _buildScreens(),
        items: _navBarsItems(),
        confineInSafeArea: true,
        backgroundColor: MyTheme.themeColor,
        handleAndroidBackButtonPress: true,
        resizeToAvoidBottomInset: true,
        stateManagement: true,

        hideNavigationBarWhenKeyboardShows: true,
        margin: const EdgeInsets.all(0.0),
        popActionScreens: PopActionScreensType.once,
        bottomScreenMargin: 0.0,
        onWillPop: (context) async {
          await showDialog(
              context: context!,
              useSafeArea: false,
              builder: (context) => CommonAlert());
          return false;
        },
        selectedTabScreenContext: (context) {
          context = context;
        },
        hideNavigationBar: _hideNavBar,

        popAllScreensOnTapOfSelectedTab: true,

        itemAnimationProperties: const ItemAnimationProperties(
          duration: Duration(milliseconds: 200),
          curve: Curves.ease,
        ),
        screenTransitionAnimation: const ScreenTransitionAnimation(
          animateTabTransition: true,
          curve: Curves.ease,
          duration: Duration(milliseconds: 200),
        ),
        navBarStyle:
            NavBarStyle.style7, // Choose the nav bar style with this property
      ),
    );
  }

您可以这样做导航到其他页面

 pushNewScreen(context,
                              screen: Loyalty(
                                menuScreenContext: context,
                              ),pageTransitionAnimation:PageTransitionAnimation.scale);
                        },

【讨论】:

  • 感谢 Nbn,所以这意味着如果我在一个屏幕中并且我想导航到第二个屏幕,我必须为底部导航添加路线,它将使用底部导航栏导航我对于大型项目是否安全?
  • 是的,它适用于您应用程序的所有屏幕
【解决方案3】:

如果您仅在HomePage(您的第一页)中定义BottomNavigationBar,则无需在所有页面中添加它。

【讨论】:

  • 但我做得对,但我有 40 页的应用程序,我无法在所有页面中显示底栏
  • 正如@vaidarbhi 所建议的,如果您在主页中定义它并将该主页导入所有其他页面,您就可以实现。
【解决方案4】:

如果您不想使用任何包来维护或缩小应用程序大小,请使用内置的 Flutter 底部导航

import 'package:flutter/material.dart';

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

  @override
  State<Mynavigation> createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<Mynavigation> {
  int _selectedIndex = 0;
  static const TextStyle optionStyle =
  TextStyle(fontSize: 30, fontWeight: FontWeight.bold);
   List<Widget> _widgetOptions = <Widget>[
   Home(),Business(),School(), Settings()
    
  ];

  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(
        type: BottomNavigationBarType.fixed,
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
            backgroundColor: Colors.red,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
            backgroundColor: Colors.green,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
            backgroundColor: Colors.purple,
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.settings),
            label: 'Settings',
            backgroundColor: Colors.pink,
          ),
        ],
        currentIndex: _selectedIndex,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
      ),
    );
  }
}

你确实注意到这条线有 家庭(),商业(),学校(),设置(),

这些应该是您要导航到的各个页面。所以请更改它们以指向您要使用的页面。

然后再做一件事,只需将 Mynavigation 替换为 WorkerHomeScreen 就可以了,

如果您使用颤振 sdk >2.12.0 请在此行使用

static const List<Widget> _widgetOptions = <Widget>[

否则,如果您的 sdk 低于 2.12.0,则使用

 List<Widget> _widgetOptions = <Widget>[

如果有任何问题,我会等待

祝你好运

【讨论】:

  • 感谢您的回答 smith,但我想像在 YouTube 中导航一样导航,这不是我的答案
【解决方案5】:

您可以简单地使用脚手架属性添加 BottomNevigatioBar 并将多个 Page 添加到列表中。希望你得到你的解决方案

import 'package:flutter/material.dart';
import 'package:traveling/helpers/AppColors.dart';
import 'package:traveling/screens/Employee/home/Home.dart';
import 'package:traveling/screens/Employee/profile/Profile.dart';
import 'package:traveling/screens/Employee/setting/Setting.dart';



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

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

class _EmployeeBottomNavBarState extends State<EmployeeBottomNavBar> {
  int pageIndex = 0;
  bool visible = true;

  List<Widget> pageList = <Widget>[EmployeeHome(), Profile(leadingIcon: false,), Setting()];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        body: pageList[pageIndex],
        bottomNavigationBar: BottomNavigationBar(
            fixedColor: Colors.redAccent[400],
            currentIndex: pageIndex,
            onTap: (value) {
              setState(() {
                pageIndex = value;
              });
            },
            // type: BottomNavigationBarType.fixed,
            items: [
              BottomNavigationBarItem(

                  activeIcon: Container(
                    height: 40,
                    width: 80,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Color(0xff2161c0),
                    ),
                    child: Icon(
                      Icons.home,
                      color: AppColors.white,
                    ),
                  ),
                  icon: Icon(
                    Icons.home,
                    color: Color(0xff2161c0),
                  ),
                  label: ""),
              BottomNavigationBarItem(
                  activeIcon: Container(
                    height: 40,
                    width: 80,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: Color(0xff2161c0),
                    ),
                    child: Icon(
                      Icons.person,
                      color: AppColors.white,
                    ),
                  ),
                  icon: Icon(
                    Icons.person,
                    color: AppColors.baseLightBlueColor,
                  ),
                  label: ""),
              BottomNavigationBarItem(
                  activeIcon: Container(
                    height: 40,
                    width: 80,
                    decoration: BoxDecoration(
                      shape: BoxShape.circle,
                      color: AppColors.baseLightBlueColor,
                    ),
                    child: Icon(
                      Icons.settings,
                      color: AppColors.white,
                    ),
                  ),
                  icon: Icon(
                    Icons.settings,
                    color: AppColors.baseLightBlueColor,
                  ),
                  label: ""),
            ]
        )
    );
  }
}

【讨论】:

  • 不,这不是我的答案
猜你喜欢
  • 1970-01-01
  • 2020-07-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-29
  • 2020-02-07
相关资源
最近更新 更多