向下滚动时隐藏的Flutter TabBar和SliverAppBar

时间:2019-03-15 16:52:44

标签: android dart flutter flutter-layout flutter-sliver

我正在尝试使用顶部的应用程序栏和下面的标签栏创建一个应用程序。向下滚动时,应通过移出屏幕来隐藏该栏(但应保留选项卡),而向上滚动时,应再次显示该应用程序栏。可以在WhatsApp中看到此行为。请观看this视频以进行演示。 (摘自Material.io)。 This的行为与此类似,尽管应用程序栏和标签栏隐藏在滚动条上,所以这并非我要查找的行为。

我已经能够实现自动隐藏,但是存在一些问题:

  1. 我必须将snap中的SliverAppBar设置为true。没有此功能,当我向上滚动时,应用程序栏将不会显示。

    尽管这是可行的,但这不是我想要的行为。我希望应用程序栏显示流畅(类似于WhatsApp),而不是即使滚动很少也不会显示。

  2. 当我向下滚动并更改标签时,一小部分内容被遮挡掉了。

    下面是显示行为的GIF:

    GIF demonstrating output

    (当我向下滚动listView(tab1),然后移回tab2时,请参阅该部分)

这是DefaultTabController的代码:

DefaultTabController(
  length: 2,
  child: new Scaffold(
    body: new NestedScrollView(
      headerSliverBuilder:
          (BuildContext context, bool innerBoxIsScrolled) {
        return <Widget>[
          new SliverAppBar(
            title: Text("Application"),
            floating: true,
            pinned: true,
            snap: true,    // <--- this is required if I want the application bar to show when I scroll up
            bottom: new TabBar(
              tabs: [ ... ],    // <-- total of 2 tabs
            ),
          ),
        ];
      },
      body: new TabBarView(
        children: [ ... ]    // <--- the array item is a ListView
      ),
    ),
  ),
),

如果需要,完整的代码在此GitHub repository中。 main.darthere

我还发现了以下相关问题:Hide Appbar on Scroll Flutter?。但是,它没有提供解决方案。同样的问题仍然存在,并且当您向上滚动时,SliverAppBar将不会显示。 (因此,snap: true是必需的)

我还在Flutter的GitHub上找到了this issue。 (编辑:,有人评论说他们正在等待Flutter团队解决此问题。是否有没有解决办法?)

这是flutter doctor -vPastebin的输出。发现了某些问题,但是据我了解,它们不会产生影响。

4 个答案:

答案 0 :(得分:6)

通过使用带有 NestedScrollView 的 SliverAppbar,我能够使带有 Tabbar 的浮动 Appbar 类似于 WhatsApp 的浮动 Appbar。

在 NestedScrollView 中添加 floatHeaderSliv​​ers: true 和

固定:真,浮动:真,在 SliverAppBar 中

Link to working code sample

import 'dart:math';
import 'package:flutter/material.dart';

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: CustomSliverAppbar(),
    );
  }
}

class CustomSliverAppbar extends StatefulWidget {
  @override
  _CustomSliverAppbarState createState() => _CustomSliverAppbarState();
}

class _CustomSliverAppbarState extends State<CustomSliverAppbar>
    with SingleTickerProviderStateMixin {
  TabController _tabController;

  @override
  void initState() {
    _tabController = TabController(
      initialIndex: 0,
      length: 2,
      vsync: this,
    );
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: NestedScrollView(
        floatHeaderSlivers: true,
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              title: Text(
                "WhatsApp type sliver appbar",
              ),
              centerTitle: true,
              pinned: true,
              floating: true,
              bottom: TabBar(
                  indicatorColor: Colors.black,
                  labelPadding: const EdgeInsets.only(
                    bottom: 16,
                  ),
                  controller: _tabController,
                  tabs: [
                    Text("TAB A"),
                    Text("TAB B"),
                  ]),
            ),
          ];
        },
        body: TabBarView(
          controller: _tabController,
          children: [
            TabA(),
            const Center(
              child: Text('Display Tab 2',
                  style: TextStyle(fontSize: 16, fontWeight: FontWeight.bold)),
            ),
          ],
        ),
      ),
    );
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }
}

class TabA extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scrollbar(
      child: ListView.separated(
        separatorBuilder: (context, child) => Divider(
          height: 1,
        ),
        padding: EdgeInsets.all(0.0),
        itemCount: 30,
        itemBuilder: (context, i) {
          return Container(
            height: 100,
            width: double.infinity,
            color: Colors.primaries[Random().nextInt(Colors.primaries.length)],
          );
        },
      ),
    );
  }
}

enter image description here

答案 1 :(得分:2)

---编辑1-

好的,所以我为您快速整理了一些内容。我跟随这篇文章(由Flutter的主要开发者之一Emily Fortuna撰写)来更好地理解Slivers。

Medium: Slivers, Demystified

但是随后发现这则Youtube视频基本上使用了您的代码,因此我选择了此视频,而不是尝试找出有关Slivers的每个小细节。

Youtube: Using Tab and Scroll Controllers and the NestedScrollView in Dart's Flutter Framework

证明您的代码正确无误。您可以在SliverAppBar中使用NestedScrollView(上次尝试不是这种情况),但是我做了一些更改。我将在代码后进行解释:

import 'package:flutter/material.dart';

import 'dart:math';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage>  with SingleTickerProviderStateMixin /*<-- This is for the controllers*/ {
  TabController _tabController; // To control switching tabs
  ScrollController _scrollViewController; // To control scrolling

  List<String> items = [];
  List<Color> colors = [Colors.red, Colors.green, Colors.yellow, Colors.purple, Colors.blue, Colors.amber, Colors.cyan, Colors.pink];
  Random random = new Random();

  Color getRandomColor() {
    return colors.elementAt(random.nextInt(colors.length));
  }

  @override
  void initState() {
    super.initState();
    _tabController =TabController(vsync: this, length: 2);
    _scrollViewController =ScrollController();
  }

  @override
  void dispose() {
    super.dispose();
    _tabController.dispose();
    _scrollViewController.dispose();
  }

  @override
  Widget build(BuildContext context) {

 // Init the items
    for (var i = 0; i < 100; i++) {
      items.add('Item $i');
    }

    return SafeArea(
      child: NestedScrollView(
        controller: _scrollViewController,
        headerSliverBuilder: (BuildContext context, bool boxIsScrolled) {
          return <Widget>[
            SliverAppBar(
              title: Text("WhatsApp using Flutter"),
              floating: true,
              pinned: false,
              snap: true,
              bottom: TabBar(
                tabs: <Widget>[
                  Tab(
                    child: Text("Colors"),
                  ),
                  Tab(
                    child: Text("Chats"),
                  ),
                ],
                controller: _tabController,
              ),
            ),
          ];
        },
        body: TabBarView(
              controller: _tabController,
              children: <Widget>[
                ListView.builder(
                  itemBuilder: (BuildContext context, int index) {
                      Color color = getRandomColor();
                      return Container(
                        height: 150.0,
                        color: color,
                        child: Text(
                          "Row $index",
                          style: TextStyle(
                            color: Colors.white,
                          ),
                        ),
                      );
                    },
                    //physics: NeverScrollableScrollPhysics(), //This may come in handy if you have issues with scrolling in the future
                  ),

                  ListView.builder(
                    itemBuilder: (BuildContext context, int index) {
                      return Material(
                        child: ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Colors.blueGrey,
                          ),
                          title: Text(
                            items.elementAt(index)
                            ),
                        ),
                      );
                    },
                    //physics: NeverScrollableScrollPhysics(),
                  ),
              ],
            ),
      ),
    );

  }
}

好的,这样的解释。

  1. 使用StatefulWidget

    Flutter中的大多数小部件都将是有状态的,但这取决于具体情况。我认为在这种情况下会更好,因为您使用的ListView可能会随着用户添加或删除对话/聊天而改变。

  2. SafeArea,因为此小部件很棒。

    Flutter Docs: SafeArea

  3. 上进行阅读
  4. 控制器

    我认为一开始这是个大问题,但也许还有其他问题。但是,如果要处理Flutter中的自定义行为,通常应该制作自己的控制器。因此,我制作了_tabController_scrollViewController(我认为我并没有从中获得全部功能,即跟踪制表符之间的滚动位置,但它们在基础上起作用)。用于TabBarTabView的选项卡控制器应该相同。

  5. Material之前的ListTile小部件

    您可能迟早会发现这一点,但是ListTile小部件是“材质”小部件,因此根据我最初尝试渲染它时得到的输出,需要“材料祖先”小部件。因此,我为此省了一点头痛。我认为这是因为我没有使用Scaffold。 (当您使用不带“材质祖先”小部件的“材质”小部件时,请记住这一点)

希望这可以帮助您入门,如果您需要任何帮助,只需给我发消息或将我添加到您的Github仓库中,我会做的。


---原始---

我也在Reddit上回答了您,希望您很快能看到这两个之一。

SliverAppBar信息

您希望SliverAppBar具有的关键属性是:

floating: Whether the app bar should become visible as soon as the user scrolls towards the app bar.
pinned: Whether the app bar should remain visible at the start of the scroll view. (This is the one you are asking about)
snap: If snap and floating are true then the floating app bar will "snap" into view.

所有这些都来自Flutter SliverAppBar Docs。他们有很多动画示例,具有不同的浮动,固定和捕捉组合。

因此对您来说,以下方法应该起作用:

SliverAppBar(
            title: Text("Application"),
            floating: true, // <--- this is required if you want the appbar to come back into view when you scroll up
            pinned: false, // <--- this will make the appbar disappear on scrolling down
            snap: true,    // <--- this is required if you want the application bar to 'snap' when you scroll up (floating MUST be true as well)
            bottom: new TabBar(
              tabs: [ ... ],    // <-- total of 2 tabs
            ),
          ),

带有SliverAppBar的ScrollView

回答NestedScrollView的基本问题。根据文档(与上述相同),SliverAppBar为:

  

CustomScrollView集成在一起的材料设计应用栏。

因此,您不能使用NestedScrollView。您需要使用CustomScrollView这是Sliver类的预期用途,但可以在{ NestedScrollView签出docs

答案 2 :(得分:1)

您需要使用SliverOverlapAbsorber/SliverOverlapInjector,以下代码对我有用(Full Code):

@override
  Widget build(BuildContext context) {
    return Material(
      child: Scaffold(
        body: DefaultTabController(
          length: _tabs.length, // This is the number of tabs.
          child: NestedScrollView(
            headerSliverBuilder:
                (BuildContext context, bool innerBoxIsScrolled) {
              // These are the slivers that show up in the "outer" scroll view.
              return <Widget>[
                SliverOverlapAbsorber(
                  // This widget takes the overlapping behavior of the SliverAppBar,
                  // and redirects it to the SliverOverlapInjector below. If it is
                  // missing, then it is possible for the nested "inner" scroll view
                  // below to end up under the SliverAppBar even when the inner
                  // scroll view thinks it has not been scrolled.
                  // This is not necessary if the "headerSliverBuilder" only builds
                  // widgets that do not overlap the next sliver.
                  handle:
                      NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                  child: SliverSafeArea(
                    top: false,
                    sliver: SliverAppBar(
                      title: const Text('Books'),
                      floating: true,
                      pinned: true,
                      snap: false,
                      primary: true,
                      forceElevated: innerBoxIsScrolled,
                      bottom: TabBar(
                        // These are the widgets to put in each tab in the tab bar.
                        tabs: _tabs.map((String name) => Tab(text: name)).toList(),
                      ),
                    ),
                  ),
                ),
              ];
            },
            body: TabBarView(
              // These are the contents of the tab views, below the tabs.
              children: _tabs.map((String name) {
                return SafeArea(
                  top: false,
                  bottom: false,
                  child: Builder(
                    // This Builder is needed to provide a BuildContext that is "inside"
                    // the NestedScrollView, so that sliverOverlapAbsorberHandleFor() can
                    // find the NestedScrollView.
                    builder: (BuildContext context) {
                      return CustomScrollView(
                        // The "controller" and "primary" members should be left
                        // unset, so that the NestedScrollView can control this
                        // inner scroll view.
                        // If the "controller" property is set, then this scroll
                        // view will not be associated with the NestedScrollView.
                        // The PageStorageKey should be unique to this ScrollView;
                        // it allows the list to remember its scroll position when
                        // the tab view is not on the screen.
                        key: PageStorageKey<String>(name),
                        slivers: <Widget>[
                          SliverOverlapInjector(
                            // This is the flip side of the SliverOverlapAbsorber above.
                            handle:
                                NestedScrollView.sliverOverlapAbsorberHandleFor(
                                    context),
                          ),
                          SliverPadding(
                            padding: const EdgeInsets.all(8.0),
                            // In this example, the inner scroll view has
                            // fixed-height list items, hence the use of
                            // SliverFixedExtentList. However, one could use any
                            // sliver widget here, e.g. SliverList or SliverGrid.
                            sliver: SliverFixedExtentList(
                              // The items in this example are fixed to 48 pixels
                              // high. This matches the Material Design spec for
                              // ListTile widgets.
                              itemExtent: 60.0,
                              delegate: SliverChildBuilderDelegate(
                                (BuildContext context, int index) {
                                  // This builder is called for each child.
                                  // In this example, we just number each list item.
                                  return Container(
                                      color: Color((math.Random().nextDouble() *
                                                      0xFFFFFF)
                                                  .toInt() <<
                                              0)
                                          .withOpacity(1.0));
                                },
                                // The childCount of the SliverChildBuilderDelegate
                                // specifies how many children this inner list
                                // has. In this example, each tab has a list of
                                // exactly 30 items, but this is arbitrary.
                                childCount: 30,
                              ),
                            ),
                          ),
                        ],
                      );
                    },
                  ),
                );
              }).toList(),
            ),
          ),
        ),
      ),
    );
  }

答案 3 :(得分:1)

更新 - Sliver 应用栏扩展

如果您想在有人向上滚动时立即看到 Sliver App Bar 展开,即不是一直滚动到顶部而是一点点,那么只需在代码中将 snap: false 更改为 snap: true :)< /p>


解决方案[修复所有点]

在谷歌、stackoverflow、github 问题、reddit 上冲浪了几个小时之后。我终于可以提出解决以下问题的解决方案:

  1. 标题被隐藏的 Sliver 应用栏,向下滚动后只有标签栏可见。当您到达顶部时,您会再次看到标题。

  2. MAJOR :当您在 Tab 1 中滚动然后导航到 Tab 2 时,您不会看到任何重叠。 Tab 2 的内容不会被 Sliver App bar 挡住。

  3. List 中最顶部元素的 Sliver Padding 为 0。

  4. 保留单个标签中的滚动位置

下面是代码,我会尝试解释一下(dartpad preview) :

import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  static const String _title = 'Flutter Code Sample';

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: _title,
      home: MyStatelessWidget(),
    );
  }
}

class MyStatelessWidget extends StatelessWidget {
  const MyStatelessWidget({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final List<String> _tabs = <String>['Tab 1', 'Tab 2'];
    return DefaultTabController(
      length: _tabs.length,
      child: Scaffold(
        body: NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              SliverOverlapAbsorber(
                handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                sliver: SliverAppBar(
                  title: const Text('Books'),
                  floating: true,
                  pinned: true,
                  snap: false,
                  forceElevated: innerBoxIsScrolled,
                  bottom: TabBar(
                    tabs: _tabs.map((String name) => Tab(text: name)).toList(),
                  ),
                ),
              ),
            ];
          },
          body: TabBarView(
            children: _tabs.map((String name) {
              return SafeArea(
                top: false,
                bottom: false,
                child: Builder(
                  builder: (BuildContext context) {
                    return CustomScrollView(
                      key: PageStorageKey<String>(name),
                      slivers: <Widget>[
                        SliverOverlapInjector(
                          handle: NestedScrollView.sliverOverlapAbsorberHandleFor(context),
                        ),
                        SliverPadding(
                          padding: const EdgeInsets.all(8.0),
                          sliver: SliverList(
                            delegate: SliverChildBuilderDelegate(
                              (BuildContext context, int index) {
                                return ListTile(
                                  title: Text('Item $index'),
                                );
                              },
                              childCount: 30,
                            ),
                          ),
                        ),
                      ],
                    );
                  },
                ),
              );
            }).toList(),
          ),
        ),
      ),
    );
  }
}

在 dartpad 中测试你想要的一切,一旦你没问题,那么让我们试着了解这里发生了什么。

大部分代码来自flutter documentation of NestedScrollView

他们在评论中提到的很好。我不是专家,所以我只想强调一下我认为解决了大部分问题的方法。

我认为这里有两点很关键:

  1. SliverOverlapAbsorber & SliverOverlapInjector
  2. 使用 SliverList 而不是 ListView

我们看到的额外空间或者sliver app bar消耗的空间和第一个列表项重叠的空间主要是通过使用以上两点来解决的。

为了记住标签的滚动位置,他们在 PageStorageKey 中添加了 CustomScrollView

key: PageStorageKey<String>(name),

name 只是一个字符串 -> 'Tab 1'

他们还在文档中提到我们可以使用 SliverFixedExtentList、SliverGrid,基本上是 Sliver 小部件。现在应该在需要时使用 Sliver 小部件。在其中一个 Flutter Youtube 视频(官方频道)中,他们提到 ListView、GridView 都是 Slivers 的高级实现。所以如果你想超级自定义滚动或外观行为,Slivers 是低级的东西。

如果我遗漏了什么或说错了,请在评论中告诉我。