首页 > 解决方案 > [Flutter]SliverAppBar在NestedScrollView中向下滚动时如何保持flexibleSpace展开?

问题描述

在 NestedScrollView 中向下滚动时如何保持 SliverAppBar 展开?

我想更改名为“_locked”的标志来锁定 SliverAppBar 的高度,但我不知道该怎么做。

可能需要使用 SliverPersistentHeader 小部件?

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

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

class _MyHomePageState extends State<MyHomePage> {
  final double expanded = 200;
  bool _locked = false;

  @override
  Widget build(BuildContext context) {
    final top = MediaQuery.of(context).padding.top;
    return Scaffold(
      body: NestedScrollView(
        headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
          return [
            SliverAppBar(
              pinned: true,
              floating: true,
              title: Text(widget.title),
              expandedHeight: expanded - top,
              flexibleSpace: LayoutBuilder(
                builder: (BuildContext context, BoxConstraints constraints) {
                  return Container(height: expanded, color: Colors.red);
                },
              ),
            ),
          ];
        },
        body: ListView(
          children: ListTile.divideTiles(
              context: context,
              tiles: List.generate(
                  50,
                  (index) => ListTile(
                        title: Text('Index: $index'),
                      ))).toList(),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(_locked ? Icons.lock_open : Icons.lock_outline),
        onPressed: () {
          /// Switch the flag
          setState(() {
            _locked = !_locked;
          });
        },
      ),
    );
  }
}

标签: flutterdart

解决方案


我相信你想绑定_locked到.SliverAppBar

我链接的文档中包含一个 gif 示例!


推荐阅读