【问题标题】:What is the best way to implement screens that always have AppBar and BottomNavigationBar?实现始终具有 AppBar 和 BottomNavigationBar 的屏幕的最佳方法是什么?
【发布时间】:2020-02-18 05:46:04
【问题描述】:

我有 3 个屏幕 - home、friends 和 profile。我希望 AppBar 和 BottomNavigationBar 始终出现在我的所有屏幕中。现在,我在main.dart 文件的Scaffold 中定义了AppBar 和BottomNavigationBar。每当在BottomNavigationBar 上点击一个选项时,Scaffold 正文就会被替换为所选屏幕的内容。

ma​​in.dart:

Widget build(BuildContext context) {
return MaterialApp(
  home: Scaffold(
    appBar: AppBar(),
    body: SafeArea(
      child: Container(
        child: _pageOptions[_selectedPage],
      ),
    ),
    bottomNavigationBar: BottomNavigationBar(
      currentIndex: _selectedPage,
      onTap: (int index) {
        setState(() {
          _selectedPage = index;
        });
      },
      items: [
        BottomNavigationBarItem(
            icon: Icon(Icons.home), title: Text('Home')),
        BottomNavigationBarItem(
            icon: Icon(Icons.people), title: Text('Friends')),
        BottomNavigationBarItem(
            icon: Icon(Icons.person), title: Text('Profile'))
      ],
    ),
  ),
  routes: <String, WidgetBuilder>{
    '/home': (BuildContext context) => Home(),
    '/friends': (BuildContext context) => Friends(),
  },
);
}

现在,我有一个自定义的avatar 小部件,我在home 屏幕中重复使用了它。单击avatar 时,我想显示friends 屏幕。我在avatar 的onTap 方法中尝试了这段代码:

{Navigator.pushNamed(context, '/friends')},

friends.dart:

Widget build(BuildContext context) {
    return Container(
        child: Text('Friends'),
    );
}

点击avatar 时,我会看到friends 屏幕,但其他所有内容都丢失了(AppBar、BottomNavigationBar 等)。

我如何实现这一目标?我应该从我的所有 3 个屏幕返回一个带有AppBar、BottomNavigationBar 等的脚手架吗?这会对性能产生负面影响吗?或者有没有办法通过在main.dart 中替换Scaffold 的主体来做到这一点?

【问题讨论】:

    标签: flutter flutter-navigation


    【解决方案1】:

    是的,您需要在所有三个屏幕中返回一个带有 appbar 的脚手架。您可以将 appbar 放在一个单独的无状态小部件类中,并在所有三个脚手架中使用它。底部导航栏也是如此。您可以尝试将返回的小部件保留在构建方法“const”中。 appbar 将无法使用,因为标题会有所不同。它不会被重建,所以不用担心性能。

    【讨论】:

      猜你喜欢
      • 2021-06-06
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 2016-12-24
      • 1970-01-01
      • 2010-09-09
      相关资源
      最近更新 更多