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

the*_*hem 8 android dart flutter flutter-sliver flutter-layout

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

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

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

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

  2. 当我向下滚动并更改选项卡时,部分内容会被遮挡掉。

    以下是显示行为的GIF:

    GIF展示输出

    (当我在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
      ),
    ),
  ),
),
Run Code Online (Sandbox Code Playgroud)

如果需要,完整的代码在此GitHub存储库中main.dart这里

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

我还在Flutter的GitHub上发现了此问题。(编辑:有人评论说他们正在等待Flutter团队解决此问题。是否有没有解决方案的可能性?)

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

kru*_*kat 14

更新 - Sliver 应用栏扩展

如果您希望看到 Sliver 应用栏在有人向上滚动时立即展开,即不是一直滚动到顶部,而是滚动一点点,那么只需在代码中更改snap: false为:)snap: true


解决方案[固定所有点]

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

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

  2. 主要:当您滚动选项卡 1 然后导航到选项卡 2 时,您不会看到任何重叠。Tab 2 的内容不会被 Sliver App 栏遮挡。

  3. 列表中最顶部元素的条子填充为 0。

  4. 保留各个选项卡中的滚动位置

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

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

Run Code Online (Sandbox Code Playgroud)

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

大部分代码来自NestedScrollView的flutter文档

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

我认为这里有两件事至关重要:

  1. SliverOverlapAbsorber&SliverOverlapInjector
  2. 使用SliverList代替ListView

无论我们看到什么额外的空间,或者条子应用栏消耗的空间以及第一个列表项重叠的空间,主要是通过使用上述两点来解决的。

为了记住选项卡的滚动位置,他们PageStorageKey在里面添加了CustomScrollView

key: PageStorageKey<String>(name),
Run Code Online (Sandbox Code Playgroud)

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

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

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

  • 谢谢您的回答!此解决方案确实解决了重叠问题,但问题是我必须一直向上滚动才能再次查看应用程序栏。我正在寻找类似 Android WhatsApp 的应用栏行为 (2认同)
  • `snap: true` 将解决你的问题:)我刚刚在 dartpad 中测试了它。向下滚动,然后向上滚动一点,离开鼠标触摸板,您将看到 Sliver 应用栏平滑展开:) (2认同)
  • 谢谢,这有效!您认为您可以在答案中添加有关将 snap 设置为 true 的部分吗?我认为如果人们将来搜索像 WhatsApp 这样的行为,这可能会对他们有所帮助 (2认同)

Kap*_*ahu 8

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

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

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

链接到工作代码示例

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)],
          );
        },
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


Tan*_*vis 7

--- 编辑 1 --

好的,所以我为你快速整理了一些东西。我关注了这篇文章(由 Emily Fortuna 撰写,她是 Flutter 的主要开发者之一)以更好地理解 Slivers。

媒介:裂片妖,揭开神秘面纱

但后来发现这个 Youtube 视频基本上使用了你的代码,所以我选择了这个,而不是试图找出关于 Slivers 的每一个小细节。

Youtube:在 Dart 的 Flutter 框架中使用 Tab 和 Scroll Controllers 和 NestedScrollView

事实证明,您的代码走在正确的轨道上。您可以使用SliverAppBarNestedScrollView(我上次尝试时不是这种情况),但我做了一些更改。我将在我的代码之后解释:

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(),
                  ),
              ],
            ),
      ),
    );

  }
}
Run Code Online (Sandbox Code Playgroud)

好的等等解释。

  1. 用一个 StatefulWidget

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

  2. SafeArea 因为这个小部件很棒。

    Flutter Docs上阅读它:SafeArea

  3. 控制器

    我认为这起初是个大问题,但也许是其他问题。但是,如果您在 Flutter 中处理自定义行为,通常应该制作自己的控制器。所以我制作了_tabController_scrollViewController(我认为我没有从它们中获得所有功能,即跟踪选项卡之间的滚动位置,但它们适用于基础知识)。您用于TabBar和 的选项卡控制器TabView应该相同。

  4. Material之前该WidgetListTile

    您可能迟早会发现这一点,但该ListTile小部件是一个 Material 小部件,因此根据我最初尝试渲染它时得到的输出,需要一个“Material 祖先小部件”。所以我用那个让你有点头疼。我想这是因为我没有使用Scaffold. (当您使用没有 Material 祖先小部件的 Material 小部件时,请记住这一点)

希望这可以帮助您入门,如果您需要任何帮助,请给我发消息或将我添加到您的 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.
Run Code Online (Sandbox Code Playgroud)

所有这些都来自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
            ),
          ),
Run Code Online (Sandbox Code Playgroud)

带有 SliverAppBar 的 ScrollView

要回答NestedScrollView. 根据文档(同上)aSliverAppBar是:

CustomScrollView.

因此你不能使用 aNestedScrollView你需要使用 a CustomScrollView这是Sliver类的预期用途,但它们可以在NestedScrollView查看文档中使用


Ism*_*OUH 5

您需要使用SliverOverlapAbsorber / SliverOverlapInjector,以下代码对我有用完整代码):

@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(),
            ),
          ),
        ),
      ),
    );
  }
Run Code Online (Sandbox Code Playgroud)