Home > Back-end >  How to scroll two SingleChildScrollView same time in Flutter?
How to scroll two SingleChildScrollView same time in Flutter?

Time:12-01

I want to scroll two SingleChildScrollView same time vertically.

enter image description here

CodePudding user response:

This code works for both SingleChildScrollViews.

import 'package:flutter/material.dart';

class ScrollTestPage extends StatefulWidget {
  const ScrollTestPage({Key? key}) : super(key: key);

  @override
  State<ScrollTestPage> createState() => _ScrollTestPageState();
}

class _ScrollTestPageState extends State<ScrollTestPage> {
  final _controller1 = ScrollController();
  final _controller2 = ScrollController();

  @override
  void initState() {
    super.initState();
    _controller1.addListener(listener1);
    _controller2.addListener(listener2);
  }

  var _flag1 = false;
  var _flag2 = false;

  void listener1() {
    if (_flag2) return;
    _flag1 = true;
    _controller2.jumpTo(_controller1.offset);
    _flag1 = false;
  }

  void listener2() {
    if (_flag1) return;
    _flag2 = true;
    _controller1.jumpTo(_controller2.offset);
    _flag2 = false;
  }

  @override
  void dispose() {
    super.dispose();
    _controller1.removeListener(listener1);
    _controller2.removeListener(listener2);
    _controller1.dispose();
    _controller2.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              controller: _controller1,
              itemBuilder: (context, i) {
                return Container(
                  margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                  child: Text('First List View $i'),
                );
              },
              itemCount: 100,
            ),
          ),
          Expanded(
            child: ListView.builder(
              controller: _controller2,
              itemBuilder: (context, i) {
                return Container(
                  margin: const EdgeInsets.fromLTRB(10, 5, 10, 5),
                  child: Text('Second List View $i'),
                );
              },
              itemCount: 100,
            ),
          ),
        ],
      ),
    );
  }
}

CodePudding user response:

You can set the controller: parameter of both SingleChildScrollView widgets to the same controller. The controller has to be initialized like this:

final ScrollController _scrollController = ScrollController(); 
  • Related