当前位置: 首页 > 知识库问答 >
问题:

带有页面视图的自定义导航栏[Flutter]

充高扬
2023-03-14

我正在尝试用PageView在Flutter中实现一个自定义的BottomNavigationBar,用于在同一支架中包含有状态小部件的不同页面之间滑动。

虽然我可以点击navbar并更改页面,但我无法在更改指示所选页面的icon_button的颜色的同时实现pageview滑动手势。我能够完美地使用BottomNavigationBarItem来完成此操作,但我想使用自定义设计。

包含不同Icon_buttons的Stack小部件是否可以转换为BottomNavigationBarItem,这样我们就可以使用onTap和currentindex函数来使其更简单?出路何在?

import 'package:app/screens/screens.dart';
import 'package:flutter/material.dart';

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

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

class _AppBottomNavState extends State<AppBottomNav> {
  int currentIndex = 0;
  var pages = [HomeScreen(), HistoryScreen(), ScanScreen(),
    BleConnectionScreen(), AccountScreen()];
  var _appPageController = PageController();

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

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.white.withAlpha(100),
      body: PageView(
        scrollDirection: Axis.horizontal,
        children: pages,
        onPageChanged: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        controller: _appPageController,
      ),
      bottomNavigationBar:
      Stack(
        children: [
          Positioned(
            bottom: 0,
            left: 0,
            child: Container(
              width: size.width,
              height: 80,
              child: Stack(
                overflow: Overflow.visible,
                children: [
                  CustomPaint(
                    size: Size(size.width, 80),
                    painter: BNBCustomPainter(),
                  ),
                  Center(
                    heightFactor: 0.6,
                    child: FloatingActionButton(backgroundColor: Colors.green[700],
                        child: Icon(Icons.search), // Analyze Button
                        elevation: 0.1,
                        onPressed: () {}),
                  ),
                  Container(
                    width: size.width,
                    height: 80,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        IconButton(
                          icon: Icon(
                            Icons.home,
                            color: currentIndex == 0 ? Colors.green[700] : Colors.grey.shade400,
                          ),
                          onPressed: () {

                            setBottomBarIndex(0);
                          },
                          splashColor: Colors.white,
                        ),
                        IconButton(
                            icon: Icon(
                              Icons.history,
                              color: currentIndex == 1 ? Colors.green[700] : Colors.grey.shade400,
                            ),
                            onPressed: () {
                              setBottomBarIndex(1);
                            }),
                        Container(
                          width: size.width * 0.20,
                        ),
                        IconButton(
                            icon: Icon(
                              Icons.bluetooth,
                              color: currentIndex == 2 ? Colors.green[700] : Colors.grey.shade400,
                            ),
                            onPressed: () {
                              setBottomBarIndex(2);
                            }),
                        IconButton(
                            icon: Icon(
                              Icons.account_circle,
                              color: currentIndex == 3 ? Colors.green[700] : Colors.grey.shade400,
                            ),
                            onPressed: () {
                              setBottomBarIndex(3);
                            }),
                      ],
                    ),
                  )
                ],
              ),
            ),
          )
        ],
      ),
    );
  }

  void _onTappedBar(int value) {
    setState(() {
      currentIndex = value;
    });
    _appPageController.jumpToPage(value);
  }
}

class BNBCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    Path path = Path();
    path.moveTo(0, 20); // Start
    path.quadraticBezierTo(size.width * 0.20, 0, size.width * 0.35, 0);
    path.quadraticBezierTo(size.width * 0.40, 0, size.width * 0.40, 20);
    path.arcToPoint(Offset(size.width * 0.60, 20), radius: Radius.circular(20.0), clockwise: false);
    path.quadraticBezierTo(size.width * 0.60, 0, size.width * 0.65, 0);
    path.quadraticBezierTo(size.width * 0.80, 0, size.width, 20);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.lineTo(0, 20);
    canvas.drawShadow(path, Colors.black, 5, true);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

共有1个答案

叶英哲
2023-03-14

您可以在下面复制、粘贴、运行完整代码
步骤1:您可以在BottomNavigationBar中删除堆栈定位并且只使用容器
步骤2:SetBottomBarindex使用_AppPageController.AnimateTopage

代码段

bottomNavigationBar: Container(
        width: size.width,
        height: 80,
        child: Stack(
          //overflow: Overflow.visible,
          children: [
            CustomPaint(

... 
setBottomBarIndex(index) {
    setState(() {
      currentIndex = index;
    });
    _appPageController.animateToPage(index,
        duration: Duration(milliseconds: 500), curve: Curves.ease);
  }

工作演示

完整代码

import 'package:flutter/material.dart';

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

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

class _AppBottomNavState extends State<AppBottomNav> {
  int currentIndex = 0;
  var pages = [
    HomeScreen(),
    HistoryScreen(),
    ScanScreen(),
    BleConnectionScreen(),
    AccountScreen()
  ];
  var _appPageController = PageController();

  setBottomBarIndex(index) {
    setState(() {
      currentIndex = index;
    });
    _appPageController.animateToPage(index,
        duration: Duration(milliseconds: 500), curve: Curves.ease);
  }

  @override
  Widget build(BuildContext context) {
    final Size size = MediaQuery.of(context).size;
    return Scaffold(
      backgroundColor: Colors.white.withAlpha(100),
      body: PageView(
        scrollDirection: Axis.horizontal,
        children: pages,
        onPageChanged: (index) {
          setState(() {
            currentIndex = index;
          });
        },
        controller: _appPageController,
      ),
      bottomNavigationBar: Container(
        width: size.width,
        height: 80,
        child: Stack(
          //overflow: Overflow.visible,
          children: [
            CustomPaint(
              size: Size(size.width, 80),
              painter: BNBCustomPainter(),
            ),
            Center(
              heightFactor: 0.6,
              child: FloatingActionButton(
                  backgroundColor: Colors.green[700],
                  child: Icon(Icons.search), // Analyze Button
                  elevation: 0.1,
                  onPressed: () {}),
            ),
            Container(
              width: size.width,
              height: 80,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  IconButton(
                    icon: Icon(
                      Icons.home,
                      color: currentIndex == 0
                          ? Colors.green[700]
                          : Colors.grey.shade400,
                    ),
                    onPressed: () {
                      setBottomBarIndex(0);
                    },
                    splashColor: Colors.white,
                  ),
                  IconButton(
                      icon: Icon(
                        Icons.history,
                        color: currentIndex == 1
                            ? Colors.green[700]
                            : Colors.grey.shade400,
                      ),
                      onPressed: () {
                        setBottomBarIndex(1);
                      }),
                  Container(
                    width: size.width * 0.20,
                  ),
                  IconButton(
                      icon: Icon(
                        Icons.bluetooth,
                        color: currentIndex == 2
                            ? Colors.green[700]
                            : Colors.grey.shade400,
                      ),
                      onPressed: () {
                        setBottomBarIndex(2);
                      }),
                  IconButton(
                      icon: Icon(
                        Icons.account_circle,
                        color: currentIndex == 3
                            ? Colors.green[700]
                            : Colors.grey.shade400,
                      ),
                      onPressed: () {
                        setBottomBarIndex(3);
                      }),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  void _onTappedBar(int value) {
    setState(() {
      currentIndex = value;
    });
    _appPageController.jumpToPage(value);
  }
}

class BNBCustomPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = new Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    Path path = Path();
    path.moveTo(0, 20); // Start
    path.quadraticBezierTo(size.width * 0.20, 0, size.width * 0.35, 0);
    path.quadraticBezierTo(size.width * 0.40, 0, size.width * 0.40, 20);
    path.arcToPoint(Offset(size.width * 0.60, 20),
        radius: Radius.circular(20.0), clockwise: false);
    path.quadraticBezierTo(size.width * 0.60, 0, size.width * 0.65, 0);
    path.quadraticBezierTo(size.width * 0.80, 0, size.width, 20);
    path.lineTo(size.width, size.height);
    path.lineTo(0, size.height);
    path.lineTo(0, 20);
    canvas.drawShadow(path, Colors.black, 5, true);
    canvas.drawPath(path, paint);
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}

void main() {
  runApp(MyApp());
}

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

class ScanScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
        child: Center(
            child: Text(
      "Scan",
      style: TextStyle(color: Colors.green),
    )));
  }
}

class HistoryScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("History"));
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Container(color: Colors.blue, child: Text("Home")));
  }
}

class AccountScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("Account"));
  }
}

class BleConnectionScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(child: Text("BleConnection"));
  }
}
 类似资料:
  • 问题内容: 我正在尝试在导航栏的中心添加自定义视图,并且正在使用以下代码对其进行测试: 我在视图控制器的viewDidLoad方法中进行设置,但是当我运行程序时,导航栏中似乎没有任何变化。 你能帮我吗? 问题答案: 这可行。初始化时给框架

  • 修改聊天页面导航栏背景色、导航栏上增加自定义按钮、修改导航栏上图标按钮颜色等 /** 聊天窗口导航栏 @param navigationBar 导航栏 */ - (void)ntalker_navigationBar:(UIView *)navigationBar { navigationBar.backgroundColor = [UIColor redColor];//修改导航栏背景色 }

  • Navbar 自定义导航栏 平台差异说明 App H5 微信小程序 支付宝小程序 百度小程序 头条小程序 QQ小程序 √ √ √ √ √ √ √ 基本使用 默认情况下,该组件只有向左的箭头,点击可以返回上一页,如果您想将自定义导航栏用在tabbar(不存在要返回的逻辑)页面,应该将is-back设置为false, 这样会隐藏左边的返回图标区域。 如果想在返回箭头的右边自定义类似"返回"字样,可以将

  • 问题内容: 我试图在 UINavigationBar的* 右侧添加 自定义视图 。我尝试了以下操作,但是视图未显示!请帮助,在此先感谢! * 问题答案: //创建uiview并添加三个自定义按钮

  • 使用父子 webview 或者同屏显示多个 webview 的性能和资源消耗较大。非必要不推荐使用同屏多 webview 的方案,推荐使用原生导航栏方案代替。可以加快窗体进入速度,内存占用更少。 通过在 mui.openWindow 的 styles 节点中设置 titleNView 节点的相关参数,可实现绘制原生导航栏控件,具体可参考 5+ webviewStyles 中的 titleNView

  • 我只想在我的wordpress主题菜单栏中添加一个快捷键,用于处理功能。 我尝试了在菜单中使用“