一尘不染

带控制器的SliverAppBar和Listview

flutter

我想有一个ListView内部NestedScrollView已经SliverAppBar崩溃了。但是,如果我将控制器添加到中ListView,它将停止工作(AppBar不会崩溃)。这是一个示例,其中left
ListView不影响SliverAppBar,但是right ListView会影响。

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: new MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> {
  ScrollController scrollController = new ScrollController();
  List<String> entries = ["a", "b", "c", "d", "e", "a", "b", "c", "d", "e"];

  @override
  Widget build(BuildContext context) {
    return new DefaultTabController(
      length: 2,
      child: new Scaffold(
        body: new NestedScrollView(
          headerSliverBuilder: (BuildContext context, bool innerBoxIsScrolled) {
            return <Widget>[
              new SliverAppBar(
                  title: new Text("My app"),
                  pinned: true,
                  expandedHeight: 150.0,
                  floating: true,
                  forceElevated: innerBoxIsScrolled,
                  bottom: new TabBar(
                    tabs: <Tab>[
                      new Tab(text: "FIRST"),
                      new Tab(text: "SECOND"),
                    ],
                  )),
            ];
          },
          body: new TabBarView(
            children: <Widget>[
              new ListView.builder(
                itemCount: entries.length,
                controller: scrollController,
                itemExtent: 60.0,
                itemBuilder: (buildContext, index) {
                  return new Text(entries[index]);
                },
              ),
              new ListView.builder(
                itemCount: entries.length,
                itemExtent: 60.0,
                itemBuilder: (buildContext, index) {
                  return new Text(entries[index]);
                },
              ),
            ],
          ),
        ),
      ),
    );
  }
}

您是否有可能在a上连接控制器ListView并仍然发出通知NestedScrollView


阅读 360

收藏
2020-08-13

共1个答案

一尘不染

如果您使用NestedScrollView,则选择让它管理每个子项的滚动位置,Scrollable就好像它们都是一个统一的可滚动性一样。没有一种方法可以Scrollable用控制器来驱动单个孩子的位置。这样做将具有挑战性,因为它可能会使NestedScrollView状态陷入混乱。但是,您并非完全不走运:

  • 您可以给控制器NestedScrollView
  • 如果您只想通知当前滚动位置或在嵌套滚动视图中发生滚动事件时进行更新,则可以将包裹在ScrollableNotificationListener以监听ScrollNotification
  • 如果要使子级Scrollable“重置”到初始滚动位置为零,则可以更改key其状态以破坏其状态。
2020-08-13