具有水平滚动和固定标题的Flutter SliverList

4

我已经尝试了一段时间,但是它无法正常工作。

我想在CustomScrollView中创建一个列表视图,并使用CupertinoSliverNavigationBarSliverList必须可以水平滚动。此外,它应该有一个头行,粘附在视图的顶部。

请参见此处的示例。请注意,正文可以水平滚动。

我想让红色标题行保持固定,以便在蓝色内容滚动时始终可见。

问题是标题行必须位于SingleChildScrollViewSizedBox内部,因为否则它将没有所需的宽度。 但是,一旦它在其中,我就无法使其固定。

非常感谢任何指针。

1个回答

4

解决方案 ^^ 使用SliverPersistentHeader使红色标题行粘性,并使用SliverList替代ListView。

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

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


 @override
   Widget build(BuildContext context) {
final scrollController = ScrollController();
return MaterialApp(
  home: Scaffold(
    body: CustomScrollView(
      slivers: [
        const CupertinoSliverNavigationBar(
          largeTitle: Text('Search'),
        ),
        //CupertinoSliverRefreshControl(),
        SliverPersistentHeader(
          pinned: true,
          delegate: _SliverAppBarDelegate(
            minHeight: 20.0,
            maxHeight: 30.0,
            child: Container(
                color: Colors.red, child: Center(child:
            Text("red header "))),
          ),
        ),

        SliverList(
          delegate: SliverChildListDelegate(
            List.generate(80, (index) => Container(
              padding: const EdgeInsets.all(5),
              color: Colors.blueAccent.shade100,
              child: const Text('bar'),
            )),
          ),
        ),

       ],
    ),
  ),
);
   }
}

class _SliverAppBarDelegate extends SliverPersistentHeaderDelegate {
   _SliverAppBarDelegate({
       required this.minHeight,
      required this.maxHeight,
      required this.child,
    });

    final double minHeight;
    final double maxHeight;
    final Widget child;

    @override
     double get minExtent => minHeight;

    @override
     double get maxExtent => math.max(maxHeight, minHeight);

    @override
     Widget build(BuildContext context,
      double shrinkOffset,
      bool overlapsContent) {
     return new SizedBox.expand(child: child);
      }

    @override
    bool shouldRebuild(_SliverAppBarDelegate oldDelegate) {
      return maxHeight != oldDelegate.maxHeight ||
      minHeight != oldDelegate.minHeight ||
       child != oldDelegate.child;
    }
   }

1
有一件事:当我滚动列表时,首先导航栏开始缩小。然后我可以在SliverPersistentHeader开始缩小之前稍微滚动一下列表。我能控制这个吗?SliverPersistentHeader能立即开始缩小吗? - wackazong
在SliverPersistentHeader小部件中,您将找到minHeight和maxHeight。如果您不希望它收缩,则minHeight和maxHeight应具有相同的值。^^ - i.AGUIR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接