可滚动的定位列表与SliverAppBar组合使用时无法正常工作

10

这是一个存储库,用于创建一个最小可重现示例。

当滚动ScrollablePositionedList.builder时,我希望SliverAppBar被隐藏。以下是相关代码片段。

          NestedScrollView(
              headerSliverBuilder: (context, innerBoxIsScrolled) => [
                    SliverAppBar(
                      backgroundColor: Colors.blue,
                      expandedHeight: 112,
                      snap: true,
                      pinned: false,
                      floating: true,
                      forceElevated: true,
                      actions: <Widget>[
                        IconButton(
                          icon: Icon(Icons.event),
                        )
                      ],
                      flexibleSpace: SafeArea(
                        child: Column(
                          children: <Widget>[
                            Container(
                              height: kToolbarHeight,
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.center,
                                mainAxisAlignment: MainAxisAlignment.center,
                                children: <Widget>[
                                  Text(
                                    'Title',
                                    style: Theme.of(context)
                                        .textTheme
                                        .title
                                        .copyWith(
                                            fontSize: 16, color: Colors.white),
                                  ),
                                  SizedBox(
                                    height: 2,
                                  ),
                                  Text(
                                    'Date',
                                    style: Theme.of(context)
                                        .textTheme
                                        .caption
                                        .copyWith(
                                            fontSize: 10, color: Colors.white),
                                  ),
                                  SizedBox(
                                    height: 2,
                                  ),
                                  Text(
                                    'Another Text',
                                    style: Theme.of(context)
                                        .textTheme
                                        .subtitle
                                        .copyWith(
                                            fontSize: 14, color: Colors.white),
                                  ),
                                ],
                              ),
                            ),
                            Expanded(
                              child: Container(
                                height: kToolbarHeight,
                                width: MediaQuery.of(context).size.width,
                                color: Colors.white,
                                child: Row(
                                  mainAxisAlignment:
                                      MainAxisAlignment.spaceEvenly,
                                  children: <Widget>[
                                    Text(
                                      'Prev',
                                    ),
                                    Text(
                                      'Next',
                                    )
                                  ],
                                ),
                              ),
                            )
                          ],
                        ),
                      ),
                    )
                  ],
              body: ScrollablePositionedList.builder(
                  physics: ScrollPhysics(),
                  itemPositionsListener: itemPositionListener,
                  itemScrollController: _itemScrollController,
                  initialScrollIndex: 0,
                  itemCount: 500,
                  itemBuilder: (BuildContext ctxt, int index) {
                    return Container(
                        margin: EdgeInsets.all(16)
                        ,
                        child: Text('$index'));
                  })),

我尝试了两种方法,但都不能正常工作。

方法1

我在ScrollablePositionedList.builder上添加了 physics:ScrollPhysics()

输出:

enter image description here

方法2

我在ScrollablePositionedList.builder上添加了 physics:NeverScrollableScrollPhysics()

SliverAppBar 这次隐藏了,但现在我无法滚动到 ScrollablePositionedList.builder 的最末尾,我的列表中有500个项目,但只能向上滚动到第14个项目,请查看输出。而且,在滚动时它也太卡了。

输出:

enter image description here

先谢谢你了。


为什么不尝试使用基于customScrollView的方法,就像这里展示的一样。https://flutter.dev/docs/cookbook/lists/floating-app-bar - Darish
2
由于ScrollablePositionedList允许滚动到特定的项目,因此这个小部件非常有用。 - Ravinder Kumar
我也遇到了同样的问题,为什么不是来自Flutter团队的任何东西都不能正常工作,真是令人沮丧。除了核心Flutter UI之外的任何内容都不总是能够正常工作。 - cs guy
4个回答

15

回答问题自己

这个问题目前没有解决方案。我已经在这里创建了一个问题。

看起来带有SliverAppBarScrollablePositionedList不能使用,直到Flutter团队添加shrinkwrap属性到ScrollablePositionedList为止。

建议添加shrinkwrap的功能请求已在此处创建。


4
你有没有找到任何替代解决方案?谢谢! - ch271828n

1

这里是一个基本的解决方法:

  • 使用ItemsPositionsListener监听列表滚动到的当前项目。
  • 然后创建布尔值来检查滚动方向和数量。
  • 这些条件控制一个AnimatedContainer,控制自定义标题的高度。
  • 将其作为子项放置在Column中,其中标题位于Flexible小部件中,以便可滚动列表在动画之前和之后正确占用空间。

虽然这很基本,没有使用NestedScrollView,但它保持了ScrollablePositionedList的使用,并通过根据设置的滚动条件滑入和滑出标题来实现类似的效果。

提供此信息以帮助其他人,直到基础问题得到解决...:)


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

class ScrollAllWords extends StatefulWidget {
  const ScrollAllWords({
    Key? key,
    required this.list,
  }) : super(key: key);

  final List<String> list;

  @override
  State<ScrollAllWords> createState() => _ScrollAllWordsState();
}

class _ScrollAllWordsState extends State<ScrollAllWords> {

/// use this listener to control the header position.
  final _itemPositionsListener = ItemPositionsListener.create();

///Can also use the ItemScrollController to animate through the list (code omitted)
final _itemScrollController = ItemScrollController();


  /// Gets the current index the list has scrolled to.
  int _currentIndex = 0;

  /// Compares against current index to determine the scroll direction.
  int _shadowIndex = 0;


  bool _reverseScrolling = false;
  bool _showHeader = true;

  @override
  void initState() {

    /// Set up the listener.
    _itemPositionsListener.itemPositions.addListener(() {
      checkScroll();
    });

    super.initState();
  }

  void checkScroll() {
    /// Gets the current index of the scroll.
    _currentIndex =
        _itemPositionsListener.itemPositions.value
            .elementAt(0)
            .index;

    /// Checks the scroll direction.
    if (_currentIndex > _shadowIndex) {
      _reverseScrolling = false;
      _shadowIndex = _currentIndex;
    }
    if (_currentIndex < _shadowIndex) {
      _reverseScrolling = true;
      _shadowIndex = _currentIndex;
    }

    /// Checks whether to show or hide the scroller (e.g. show when scrolled passed 15 items and not reversing).
    if (!_reverseScrolling && _currentIndex > 15) {
      _showHeader = false;
    } else {
      _showHeader = true;
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {

    return Column(
      children: [
        AnimatedContainer(
          duration: const Duration(milliseconds: 120),
          height: _showHeader ? 200 : 0,
          curve: Curves.easeOutCubic,

          child: Container(
            color: Colors.red,
            height: size.height * 0.20,
          ),
        ),

        Flexible(
          child: ScrollablePositionedList.builder(
            itemScrollController: _itemScrollController,
            itemPositionsListener: _itemPositionsListener,
            itemCount: widget.list.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(widget.list[index]),
              );
            },
          ),
        ),

      ],
    );
  }
}

Example


0
    It works for me
    //create list of global keys

     List<GlobalKey> _formKeys = [];
    
    
    //assign keys from your list
    
    for(int i=0 ;i< syourlist.length;i++){
    final key = GlobalKey();
    _formKeys.add(key);
    }
    
    //in list view give key as below
    
    key:_formKeys[index]
    
    
    //on button click
    
     Scrollable.ensureVisible(_formKeys[index].currentContext);

你的回答可以通过添加更多支持信息来改进。请编辑并添加进一步的细节,例如引用或文档。您可以在帮助中心找到有关如何编写良好答案的更多信息。请参阅如何回答 - Vimal Patel
1
我在你的代码中没有看到 ScrollablePositionedList - Ravinder Kumar

0
Flutter团队已经为ScrollablePositionedList添加了shrinkwrap属性。
但是ScrollablePositionedList仍然无法与SliverAppBar一起使用。

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