Flutter:ListView不可滚动,没有弹跳效果。

39

我有以下示例(在 iPhone X,iOS 11 上进行了测试):

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(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  @override
  Widget build(BuildContext context) {
    return new ListView(
      children: <Widget>[
        new Container(
          height: 40.0,
          color: Colors.blue,
        ),
        new Container(
          height: 40.0,
          color: Colors.red,
        ),
        new Container(
          height: 40.0,
          color: Colors.green,
        ),
      ]
    );
  }

}
在这种情况下,ListView 的表现就像预期的一样。我可以滚动到视口之外,然后 ListView 会反弹回来(典型的 iOS 行为)。但是当我添加一个 ScrollController 来跟踪偏移量时,滚动的行为就会发生变化:
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(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  ScrollController _controller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return new ListView(
      controller: _controller,
      children: <Widget>[
        new Container(
          height: 40.0,
          color: Colors.blue,
        ),
        new Container(
          height: 40.0,
          color: Colors.red,
        ),
        new Container(
          height: 40.0,
          color: Colors.green,
        ),
      ]
    );
  }
}
在这种情况下,滚动不再可行。为什么当我添加一个 ScrollController 后,滚动就不再可行了?同时将 physics: new BouncingScrollPhysics() 添加到 ListView 中也没有帮助。
谢谢任何帮助 :)

如果有人还没有找到解决方案,请查看此链接点击这里 - Malek Tubaisaht
就我所见,如果添加了ScrollController,为什么不再允许滚动没有人回答这个问题。 - undefined
8个回答

43
要始终启用ListView上的滚动条,您可以使用AlwaysScrollableScrollPhysics类包装所需的原始滚动物理效果。更多详细信息在这里。如果您希望,可以指定一个parent或依赖于默认设置。
以下是带有添加选项的示例:
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(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  ScrollController _controller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return new ListView(
        physics: const AlwaysScrollableScrollPhysics(), // new
        controller: _controller,
        children: <Widget>[
          new Container(
            height: 40.0,
            color: Colors.blue,
          ),
          new Container(
            height: 40.0,
            color: Colors.red,
          ),
          new Container(
            height: 40.0,
            color: Colors.green,
          ),
        ]
    );
  }
}

1
这似乎是一个可以接受的答案。我使用常规的ScrollController尝试过,并且完美运行。 - tapizquent
1
这个在桌面(macOS)应用上似乎不起作用。 - Clifton Labrum
你提出了解决问题的方法是很好的。但是你没有回答这个问题:“为什么当我添加一个ScrollController后,就无法再滚动了呢?” - undefined

24
如果您在Flutter Web上遇到此问题,则应使用ScrollConfiguration包装listview。 在ScrollConfiguration的behavior参数中添加PointerDeviceKind.mouse。 您可以查看示例
ScrollConfiguration(
behavior: ScrollConfiguration.of(context).copyWith(dragDevices: {
  PointerDeviceKind.touch,
  PointerDeviceKind.mouse,
},),
child: ListView(
  controller: _controller,
  physics: const AlwaysScrollableScrollPhysics(),
  scrollDirection: Axis.horizontal,
  children: <Widget>[
  
      for (int index = 0; index < showThumbnailList.length; index++) _thumbnail(showThumbnailList[index], index)
   
    // showThumbnailList.map((x) => _thumbnail(x) ).toList()),
  ],
),

非常感谢。这解决了我的问题。 - Rogério Pires
1
运行得非常好。有人可能会认为鼠标和触摸手势是相同的,并使用各种包装进行调试。 - SparkZeus
需要适用于Mac桌面。 - atreeon

5
只需添加AlwaysScrollableScrollPhysics
ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        children :  [...]
}

3

使用容器高度来滚动,并且使用 physics: AlwaysScrollableScrollPhysics()controller: controller

Container(
    width: 400,
    child: Drawer(
      child: Stack(children: [
        Container(
          height: MediaQuery.of(context).size.height-80,
          child: ListView(
            controller: controller,
            padding: EdgeInsets.zero,
            
            physics: AlwaysScrollableScrollPhysics(),
            children: [
              Container(
                height: 300,
                padding: EdgeInsets.symmetric(vertical: 20, horizontal: 10),
                child: DrawerHeader(
                  child:Stack(children: [
                    Center(
                      child: Column(
                        children: [
                          nullCatcher(image) == "" ? Image.asset("assets/images/doctor.png",height: 90,width: 90,) : Image.network(
                            "$image",
                            height: 90,
                            width: 90,
                          ),
                          SizedBox(width: 30,),
                          Text("$name",style: TextStyle(color: Colors.grey[700],fontWeight: FontWeight.bold,fontSize: 25),),
                          Text("$specialty",style: TextStyle(color: Colors.grey[600]),),
                        ],
                      ),
                    ),
                    Positioned(
                        right: 0,bottom: 10,
                        child: Text("Version: 1.0.0",style: TextStyle(color: Colors.orange),))
                  ],),

                ),
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 70,
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        Container(
                            height: 35,width: 35,
                            decoration: BoxDecoration(
                                color: Theme.of(context).accentColor,
                                borderRadius: BorderRadius.circular(100)
                            ),
                            child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                        SizedBox(width: 20,),
                        Text('Create Appointment'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>CreateAppointment()));
                  // Update the state of the app.
                  // ...
                },
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 70,
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        Container(
                            height: 35,width: 35,
                            decoration: BoxDecoration(
                                color: Theme.of(context).accentColor,
                                borderRadius: BorderRadius.circular(100)
                            ),
                            child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                        SizedBox(width: 20,),
                        Text('Appointment / Prescription List'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),
              Container(
                height: 70,
                padding: EdgeInsets.symmetric(horizontal: 30 ),
                color: Colors.grey[200],
                child: Row(
                  children: [
                    Container(
                        height: 35,width: 35,
                        decoration: BoxDecoration(
                            color: Theme.of(context).accentColor,
                            borderRadius: BorderRadius.circular(100)
                        ),
                        child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                    SizedBox(width: 20,),
                    Text("Clinical Options:",style: TextStyle(fontWeight: FontWeight.bold,color: Colors.grey[600]),),
                  ],
                ),
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: childHeight,
                    padding: EdgeInsets.only(left: childPaddeing),
                    // decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        lineDesign(),
                        SizedBox(width: 20,),
                        Text('Chief Complain'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 50,
                    padding: EdgeInsets.symmetric(horizontal: 45),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        lineDesign(),
                        SizedBox(width: 20,),
                        Text('On Examination'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 70,
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        Container(
                            height: 35,width: 35,
                            decoration: BoxDecoration(
                                color: Theme.of(context).accentColor,
                                borderRadius: BorderRadius.circular(100)
                            ),
                            child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                        SizedBox(width: 20,),
                        Text('Examination Category'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 70,
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        Container(
                            height: 35,width: 35,
                            decoration: BoxDecoration(
                                color: Theme.of(context).accentColor,
                                borderRadius: BorderRadius.circular(100)
                            ),
                            child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                        SizedBox(width: 20,),
                        Text('Diagnosis'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),
              ListTile(
                contentPadding: EdgeInsets.zero,
                title: Container(
                    height: 70,
                    padding: EdgeInsets.symmetric(horizontal: 30),
                    decoration: drawerListDecoration,
                    child: Row(
                      children: [
                        Container(
                            height: 35,width: 35,
                            decoration: BoxDecoration(
                                color: Theme.of(context).accentColor,
                                borderRadius: BorderRadius.circular(100)
                            ),
                            child: Icon(Icons.attach_file,color: Colors.white,size: 20,)),
                        SizedBox(width: 20,),
                        Text('Investigations'),
                      ],
                    )),
                onTap: () {
                  Navigator.pushReplacement(context, MaterialPageRoute(builder: (__)=>AppointmentList()));
                  // Navigator.pop(context);
                },
              ),

            ],
          ),
        ),
        Positioned(
            bottom: 0,
            left: 0,
            right: 0,
            child: ButtonTheme(
              child: RaisedButton(
                color: Colors.red[900],
                onPressed: (){
                  if(blocState is LogoutInLoading){}else logoutAlert(blocContext);
                },
                child: Container(
                  height: 70,
                  child:blocState is LogoutInLoading ? Container( height: 20,width: 20,margin: EdgeInsets.symmetric(vertical: 25), child: CircularProgressIndicator(valueColor: AlwaysStoppedAnimation(Colors.white),),) : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text("Sign Out",style: TextStyle(color: Colors.white,fontWeight: FontWeight.bold,fontSize: 25),),
                      SizedBox(width: 20,),
                      Icon(Icons.logout,color: Colors.white,)
                    ],
                  ),
                ),
              ),
            )
        )
      ],),
    ),
  );

2
在我的情况下,我只是为父容器添加了指定的高度,就像这样:
sizedBox(
 height:300
 child:   child: ListView.builder(
          controller: _controller,
          physics: const AlwaysScrollableScrollPhysics(),
          shrinkWrap: true,
          itemCount: news.length,
          itemBuilder: (context, index) {
            //container
          }

)

1
我认为这个解决方案不需要使用CustomScrollView,只需使用NotificationListener将ListView包装起来即可。
  Widget noti = new NotificationListener(
    child:listView,
    onNotification: (ScrollNotification note){
      print(note.metrics.pixels.toInt());
    },
  );

我已经测试过了,Bounce是有效的。

0

在macOS中

class MyCustomScrollBehavior extends MaterialScrollBehavior {
  // Override behavior methods and getters like dragDevices
  @override
  Set<PointerDeviceKind> get dragDevices => { 
    PointerDeviceKind.touch,
    PointerDeviceKind.mouse,
    // etc.
  };
}

// Set ScrollBehavior for an entire application.
MaterialApp(
  scrollBehavior: MyCustomScrollBehavior(),
  // ...
);

你在使用macOS应用程序的滚动视图时是否出现“弹跳”效果?我尝试了一下,但弹跳仍然不起作用。 - Clifton Labrum

0

我找到了一种解决方案,可以跟踪高度小于视口的列表的偏移量。在build()方法中使用NotificationListenerCustomScrollView,像这样:

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(title: 'Flutter Demo Home Page'),
    );
  }
}

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

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
  ScrollController _controller = new ScrollController();

  @override
  Widget build(BuildContext context) {
    return new NotificationListener(
      onNotification: _handleScrollPosition,
        child: new CustomScrollView(
            slivers: [
              new SliverList(
                  delegate: new SliverChildListDelegate([
                    new Container(
                      height: 40.0,
                      color: Colors.blue,
                    ),
                    new Container(
                      height: 40.0,
                      color: Colors.red,
                    ),
                    new Container(
                      height: 40.0,
                      color: Colors.green,
                    ),
                  ])
              )
            ]
        )
    );
  }

  bool _handleScrollPosition(ScrollNotification notification) {
    print(notification.metrics.pixels);
    return true;
  }
}

只要没有使用ScrollController的解决方案(或者有一个“更好”(更优雅)的解决方案),我将接受这个答案。

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