Search code examples
flutterdartexpansion

Flutter - Scroll down automatically


I try to do a ExpansionPanel who scroll automatically when I press on it. I need to scroll if I want to go to the bottom of the widget. I try with jumpTo and animateTo but not work very well.

1

Container(
                      decoration: BoxDecoration(
                          boxShadow: [BoxShadow(color: Colors.grey.withOpacity(0.5), spreadRadius: 5, blurRadius: 7, offset: Offset(0, 3))]),
                      margin: EdgeInsets.fromLTRB(8, 8, 8, 25),
                      child: ExpansionPanelList(
                          expandedHeaderPadding: EdgeInsets.zero,
                          children: [
                            ExpansionPanel(
                                headerBuilder: (context, sOpen) {
                                  return Container(
                                      padding: EdgeInsets.zero,
                                      margin: EdgeInsets.zero,
                                      child: TextButton(
                                          style: ButtonStyle(
                                            overlayColor: MaterialStateProperty.all(Colors.grey[400].withOpacity(0.5)),
                                            foregroundColor: MaterialStateProperty.all(Colors.black87),
                                          ),
                                          onPressed: () {
                                            setState(() {
                                              isOpen = !isOpen;
                                              expandList();
                                            });
                                          },
                                          child: task('Tasks (${tasks.length})', icon: Icon(Icons.supervised_user_circle, color: Colors.grey))));
                                },
                                body: Column(children: taskContains()),
                                isExpanded: isOpen,
                                backgroundColor: Color(0xfffafafa))
                          ],
                          expansionCallback: (i, iOpen) {
                            setState(() {
                              isOpen = !iOpen;
                              expandList();
                            });
                          }));

  void expandList() {
    if (isOpen) {
      controller.jumpTo(0);
      controller.animateTo((80 * tasks.length.toDouble()), duration: Duration(seconds: 1), curve: Curves.fastOutSlowIn);
    }
  }

Solution

  • The problem was when I expand, the Widget keep the old size and when I expand it, the scrollbar was at the bottom of the old widget. So we need to wait the end of the build. So I do it with that:

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
                  expandList();
                });