dart 我怎样才能在嵌套滚动视图和列表视图之间平滑地滚动,

rqqzpn5f  于 2023-02-10  发布在  其他
关注(0)|答案(1)|浏览(151)

我有以下简单的完整代码。

import 'package:flutter/material.dart';

class Profile extends StatefulWidget {
  const Profile({ Key? key, }) : super(key: key);
  @override
  ProfileState createState() => ProfileState();
}

class ProfileState extends State<Profile>{

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: NestedScrollView(
          headerSliverBuilder: (context,value){
            return[
              const SliverAppBar(
                expandedHeight: 400,
              )
            ];
          },
          body: ListView.builder(
            itemCount: 200,
            itemBuilder: (BuildContext context, int index) {
              return Center(child: Text(index.toString()));
            },
          )
      ),
    );
  }
}

在前面的代码中,一切正常,它以平滑的方式移动滚动,但当我在ListView.builder中提供ScrollController时,滚动不再平滑。
所以请我如何保持第一个结果(没有提供ScrollController)与(提供ScrollController)相同?

1szpjjfi

1szpjjfi1#

我使用CustomScrollView重新创建了您的需求,API "更难"使用,但它允许您实现更复杂的功能(如您正在做的嵌套滚动视图),因为我们可以直接访问Slivers API
您可以看到,几乎所有Flutter可滚动小部件都是CustomScrollViewScrollView的派生,后者使用了Slivers。

虽然看起来很复杂,但Sliver只是可滚动区域的一部分:

CustomScrollView(
  controller: _scrollController, 
  slivers: [
    const SliverAppBar(expandedHeight: 400),
    SliverList(
      delegate: SliverChildBuilderDelegate(
        (context, index) {
          return Center(child: Text('item $index.'));
        },
      ),
    ),
  ],
)

因此,与其创建多个滚动视图并试图将它们混合在一起(这会导致错误的行为),不如声明多个可滚动区域并将它们放在一个CustomScrollView中,就这样。
请参见以下位置的工作示例:https://dartpad.dev/?id=60cb0fa073975f3c80660815ae88af4e.

相关问题