Home > Back-end >  initialScrollOffset didn't work in SingleChildScrollView
initialScrollOffset didn't work in SingleChildScrollView

Time:09-17

enter image description here

As you can see there is a red horizontal SingleChildScrollView, it's offset will increase 20 every time I tap the scroll button.

Here is my code:

import 'package:flutter/material.dart';
import 'package:flutter_storage/managers/screen_util.dart';

class DraftPage extends StatefulWidget {
  DraftPage({Key key}) : super(key: key);

  @override
  _DraftPageState createState() => _DraftPageState();
}

class _DraftPageState extends State<DraftPage> {
  int index = 0;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Test'),
      ),
      body: Column(
        children: [
          SizedBox(
            width: ScreenUtil.screenWidth,
            height: 30,
            child: _LineView(currentIndex: index),
          ),
          SizedBox(height: 20),
          RaisedButton(
            child: Text('scroll'),
            onPressed: () {
              setState(() {
                index  ;
              });
            },
          ),
        ],
      ),
    );
  }
}

class _LineView extends StatelessWidget {
  const _LineView({Key key, @required this.currentIndex}) : super(key: key);

  final int currentIndex;

  @override
  Widget build(BuildContext context) {
    final offset = currentIndex * 20.0;
    print(offset);
    final controller =
        ScrollController(initialScrollOffset: offset, keepScrollOffset: false);
    controller.addListener(() {
      print(controller.offset);
    });

    final row = Row(
      children: [
        Container(
          width: 1000,
          height: 30,
          color: Colors.red,
          child: Text('666666666666666666666'),
        ),
      ],
    );

    final scrollView = SingleChildScrollView(
      controller: controller,
      scrollDirection: Axis.horizontal,
      child: row,
    );

    return scrollView;
  }
}

However, the offset of the scrollView didn't change at all when I tap the scroll button.

What's wrong in my code?

You can copy my code and test.

CodePudding user response:

A dirty fix is to add a key: Key(offset.toString()) to your SingleChildScrollView. This is because this view isn't awared that something has changed during the build.

A clean fix is to let the _LineView accept a scrollController, then when press the button, use scrollController.jumpTo to make offset. The controller's dispose can be done in your DraftPage.

  • Related