2

Can someone explain me where I should define a scroll controller? I have chat list view which is the body of a scrollable view. I want to be able to control the scrolling behaviour from MainView but don't know how to pass the controller down to _ChatListView. Any ideas?

mainview.dart

class MainView extends StatelessWidget {
    ...
    // is this the correct place?
    final ScrollController scrollController = ScrollController();

    @override
    Widget build(BuildContext context) {
        return new Scaffold(
            body: new ChatListView()
        );
    }
}

chatlistview.dart

class ChatListView extends StatefulWidget {
    @override
    _ChatListView createState() => _ChatListView();
}

class _ChatListView extends State< ChatListView > {
    Widget build(BuildContext context) {
        return ListView.builder(
          controller: scrollController,
          );
    }
}

1 Answer 1

2

Add a constructor and pass the controller as parameter

class MainView extends StatelessWidget {
    ...
    // is this the correct place?
    final ScrollController scrollController = ScrollController();

    @override
    Widget build(BuildContext context) {
        return new Scaffold(
            body: new ChatListView(scrollController: scrollController)
        );
    }
}
class ChatListView extends StatefulWidget {
    ChatListView({@required this.scrollController}); 

    final ScrollController scrollController;

    @override
    _ChatListView createState() => _ChatListView();
}
class _ChatListView extends State< ChatListView > {

    Widget build(BuildContext context) {
        return ListView.builder(
          controller: widget.scrollController,
          );
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Perfect, the widget object was finally what I was looking for! Thanks

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.