Flutter 底部导航,其中一页有选项卡

use*_*706 8 cross-platform dart flutter flutter-layout

我想创建一个带有底部导航栏的脚手架,以及一个始终显示当前页面标题的应用栏。当我更改底部栏选项时,内容会发生明显变化。到目前为止,经典的 NavigationBar 结构一切正常。但是当内容页面上应该有标签时,问题就开始了。我在父母脚手架中创建了我的应用栏。无论如何要向父小部件 appBar 添加选项卡?

我的 AppBar + BottomNavBar 页面:

class MainPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _MainPageState();
  }
}
class _MainPageState extends State<MainPage> {

  int _currentPageIndex;
  List<Widget> _pages = List();

  Widget _getCurrentPage() => _pages[_currentPageIndex];

  @override
  void initState() {
    setState(() {
      _currentPageIndex = 0;

      _pages.add(BlocProvider(bloc: AgendaBloc(), child: AgendaPage()));
      _pages.add(SpeakersPage());
      _pages.add(MenuPage());
    });
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar( title: 'Agenda'),
      body: _getCurrentPage(),
      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentPageIndex,
        onTap: (index){
          setState(() {
            _currentPageIndex = index;
          });
        },
        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.content_paste),
            title: Text('Agenda'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.group),
            title: Text('Speakers'),
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.menu),
            title: Text('Menu'),
          ),
        ],
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

现在假设我希望我的 AgendaPage 小部件在视图顶部显示选项卡。有没有简单的,非hacky的方法来做到这一点?

想要的效果: 标签页

无标签页

Ale*_*hov 4

您可以使用嵌套Scaffold小部件。这适用于 Flutter 1.1.8:

// This is the outer Scaffold. No AppBar here
Scaffold(
  // Workaround for https://github.com/flutter/flutter/issues/7036
  resizeToAvoidBottomPadding: false, 
  body: _getCurrentPage(),  // AppBar comes from the Scaffold of the current page 
  bottomNavigationBar: BottomNavigationBar(
    // ...
  )
)
Run Code Online (Sandbox Code Playgroud)

  • 将此答案标记为正确,因为这就是我最终所做的。似乎运作良好。以防万一有人犯了我的错误:如果您使用 StreamBuilder 构建选项卡页面,请注意它始终会发出 null 作为第一个元素。这可能会导致颤动渲染您的“无数据视图”(可能是空容器),然后渲染正确的视图。效果是,每次切换到选项卡时,选项卡都会“闪烁”。 (2认同)