简体   繁体   中英

ScrollController not attached to any scroll views

I'm using CustomScrollView, and providing it with a controller. ScrollController works, I even added a listener to it and print out the position of the scroll view.

CustomScrollView(
    controller: _scrollController,

Now, all i'm trying to do is jump to position 50.0 inside initState() function.

_scrollController.jumpTo(50.0);

But, i get the error

scrollController not attached to any scroll views

Check if the scrollController is attached to a scroll view by using its hasClients property first.

if (_scrollController.hasClients) 
    _scrollController.jumpTo(50.0);

Delaying it is not the right solution. Better to wait till the tree is done building by using

WidgetsBinding.instance
        .addPostFrameCallback((_){});

sample

WidgetsBinding.instance.addPostFrameCallback((_) {
      if(pageController.hasClients){
              pageController.animateToPage(page index, duration: Duration(milliseconds: 1), curve: Curves.easeInOut);
      }
});

要设置ScrollController的初始位置,请使用initialScrollOffset属性:

_scrollController = ScrollController(initialScrollOffset: 50.0);

@carlosx2 answer is correct but if someone wonder where to put WigetsBinding. So here it is.

@override
void initState(){
  super.initState();
  WidgetsBinding.instance.addPostFrameCallback((_){
    //write or call your logic
    //code will run when widget rendering complete
  });
}

This sometimes happens when you are attempting to bind a ScrollController to a widget that doesn't actually exist (yet). So it attempts to bind, but there is no ListView/ScrollView to bind to. Say you have this code:

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
    Expanded(
      flex: 8,
      child: Container(
        child: ListView.builder(
          controller: scrollController,
          itemCount: messages.length,
          itemBuilder: (context, index) {
            return MessageTile(message: messages[index]);
          }),
        ),
     ),
 ]),

Here we are building a ListView dynamically. Since we never declared this ListView before, the scrollController does not have anything to bind to. But this can easily be fixed:

// first declare the ListView and ScrollController

final scrollController = ScrollController(initialScrollOffset: 0);
ListView list = ListView.builder(
  controller: scrollController,
  itemCount: messages.length,
  itemBuilder: (context, index) {
    return MessageTile(message: messages[index]);
  }
);

// then inside your build function just reference the already built list

Column(
  crossAxisAlignment: CrossAxisAlignment.start,
  children: <Widget>[
    Expanded(
      flex: 8,
      child: Container(
         child: list,
      ),
    ),
  ]),

I resolved my problem using the same ScrollController to both controllers. First I create the ScrollController():

ScrollController scollBarController = ScrollController();

Inside my code:

Container(
    width: MediaQuery.of(context).size.width,
    height: MediaQuery.of(context).size.height,
    child: Scrollbar(
      controller: scollBarController,
      isAlwaysShown: true,
      child: StaggeredGridView.count(
        controller: scollBarController,
        crossAxisCount: 16,
        staggeredTiles: _staggeredTamanho,
        shrinkWrap: true,
        children: [
          ...
        ], //listStaggered,
        mainAxisSpacing: 7.0,
      ),
    ),
  ),

I have tried with above solutions but set ScrollController initialScrollOffset, checking hasClients and jumpTo, WidgetsBinding no one is working for me.

at last solved my problem by checking positions 'scrollcontroller.positions.length' like

if (_sc.positions.length == 0 || _sc.position.pixels == 0.0) {
    return Container();
}

You have to check controller positions to get rid of the error

Reference : https://api.flutter.dev/flutter/widgets/ScrollController/position.html

Initialize the scrollController:

ScrollController _scrollController = ScrollController(); 

Use the code bellow where you want to scroll:

SchedulerBinding.instance.addPostFrameCallback((_) {
  _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
});

I had this issue when using a ListView with a ScrollBar. The solution was to explicitly set the same controller to both the ScrollBar and ListView

final ScrollController _controller = ScrollController();

CupertinoScrollbar(
  controller: _controller,
  child: ListView.builder(
    controller: _controller,
                          

I solving using the same controller in Scrollbar() e ListView() widgets.

Container(
    height: 140,
    child: Scrollbar(
        controller: listviewScrollbarController,
        child: ListView(
            scrollDirection: Axis.horizontal,
            controller: listviewScrollbarController,
            children: [
                // ....
            ]
        )
    )
)

I found working solution, but frankly the method is not best practice, I suppose. In my case controller.jumpTo() was called before it was attached to any scroll view. In order to solve problem I delayed some milliseconds and then call .jumpTo(), because build will be called and controller will be attached to any scroll view.

Future.delayed(Duration(milliseconds: <some time, ex: 100>), () {
         _scrollController.jumpTo(50.0);
        });

I full agree that it is bad solution, but It can solve problem.

Use setState() method to bind to a scroll related widget (your listview etc.)

setState(() {
    topicsScrollController.animateTo(....);
});

I used this code to make the color of the appbar transparent at 0 position and black for more than 70

backgroundColor: !_scrollController.hasClients
            ? Colors.transparent
            : _scrollController.offset > 70
                ? Color.fromRGBO(7, 7, 7, 1)
                : Colors.transparent,

I had this problem, but in my case was much simpler, althought I think it worth mention:

Don't forget to attach the controller to your widget . In my case I rearrange my screens and change the PageView. No widgets bindings would fix it because it was not point to any

Declare an object of controller like this.

 final _scrollController = ScrollController();

And then provide it to both, to Scrollbar and to it child (ListView in this case)

Scrollbar(
       thumbVisibility: true,
       controller: _scrollController,
       child: ListView(
              controller: _scrollController,
              children: [
                         Text("Hello World"),
                         Text("Hello World"),
                         Text("Hello World"),
                   ],
              ),

Define a scroll conotroller;

final _scrollController = ScrollController();

Assign it to both controllers

Scrollbar(
 controller: _scrollController,
 child: ListView(
    controller: _scrollController,
    itemBuilder: ...
  )
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM