Flutter: ListView не прокручивается, не подпрыгивает

У меня есть следующий пример (протестирован на 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 не помогает.

Спасибо за любую помощь :)


person Renato Stauffer    schedule 03.01.2018    source источник
comment
если кто-то не нашел решения. см. эту ссылку Нажмите здесь   -  person Malek Tubaisaht    schedule 06.10.2019


Ответы (6)


Чтобы всегда была включена прокрутка на 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,
          ),
        ]
    );
  }
}
person Fabio Veronese    schedule 04.01.2018
comment
Это действительно приемлемый ответ. Я пробовал это с обычным ScrollController и отлично работает. - person Jose Tapizquent; 22.07.2019

Создает физику прокрутки с использованием AlwaysScrollableScrollPhysics, который всегда позволяет пользователю прокручивать.

Для прокрутки с эффектом отскока Просто введите физику: BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics) в свой скроллер. Это сделает его всегда прокручиваемым, даже если нет содержимого, которое переполняется

const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics())

Вот полный пример

ListView(
  padding: EdgeInsets.all(8.0),
  physics: const BouncingScrollPhysics(parent: AlwaysScrollableScrollPhysics()),
  children: _listData.map((i) {
    return ListTile(
      title: Text("Item $i"),
    );
  }).toList(),
);

введите описание изображения здесь

person Paresh Mangukiya    schedule 02.10.2020
comment
Но это не работает, если в списке всего 3-5 пунктов. Он отскакивает только в конце списка, а не наверху. - person JayVDiyk; 17.11.2020
comment
@JayVDiyk просто сделай shrinkWrap: true - person intraector; 11.12.2020
comment
@intraector для меня все наоборот, shrinkWrap: true он не отскакивает вверх с несколькими элементами, shrinkWrap: false делает свое дело - person jack_the_beast; 01.04.2021

Просто добавьте AlwaysScrollableScrollPhysics

ListView(
        physics: const AlwaysScrollableScrollPhysics(),
        children :  [...]
}
person Sanjayrajsinh    schedule 25.02.2020

Я нашел решение, как отслеживать смещение со списками, которые имеют меньшую высоту содержимого, чем область просмотра. Используйте NotificationListener вместе с CustomScrollView в методе build() следующим образом:

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 (или «лучшего» (более элегантного)), я приму это как ответ.

person Renato Stauffer    schedule 03.01.2018

Я думаю, что это решение лучше без CustomScrollView. Просто используйте NotificationListener, чтобы обернуть ListView.

  Widget noti = new NotificationListener(
    child:listView,
    onNotification: (ScrollNotification note){
      print(note.metrics.pixels.toInt());
    },
  );

Я проверил, отскок эффективен

person ken    schedule 22.07.2019

**

Используйте высоту контейнера для прокрутки, а также используйте физику: 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,)
                    ],
                  ),
                ),
              ),
            )
        )
      ],),
    ),
  );
person Rasel Khan    schedule 13.12.2020