Enable horizontal dragging of a ListView with a mouse in Flutter

Fri, Jan 12, 2024

Read in 2 minutes

To enable horizontal dragging of a `ListView` widget with a mouse in Flutter, you can use a combination of the `ListView.builder`, a `ScrollController`, and a `GestureDetector`

Here’s an example:

import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // Create a ScrollController
  ScrollController _scrollController = ScrollController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Horizontal ListView Example'),
      ),
      body: GestureDetector(
        // Use GestureDetector to detect horizontal drag gestures
        onHorizontalDragUpdate: (details) {
          // Update the scroll position based on the drag distance
          _scrollController
              .jumpTo(_scrollController.offset - details.primaryDelta!);
        },
        child: ListView.builder(
          // Set the scroll direction to horizontal
          scrollDirection: Axis.horizontal,
          controller: _scrollController, // Attach the controller to the ListView
          itemCount: 10,
          itemBuilder: (context, index) {
            return Container(
              width: 200,
              margin: EdgeInsets.all(8),
              color: Colors.blue,
              child: Center(
                child: Text('Item $index', style: TextStyle(color: Colors.white)),
              ),
            );
          },
        ),
      ),
    );
  }
}

In this example:

  1. We use a GestureDetector to detect horizontal drag gestures.
  2. The onHorizontalDragUpdate callback is triggered when the user drags horizontally.
  3. Inside the callback, we update the scroll position of the ListView based on the drag distance using the jumpTo method of the ScrollController.
  4. The ListView.builder is set to have a horizontal scroll direction using scrollDirection: Axis.horizontal.

This allows you to horizontally drag the ListView with the mouse. Adjust the container width and other properties based on your specific layout requirements.


Shohruh AK



Category:

Flutter

Tags:



See Also

New App Signing feature provided by Google Play
Tracking File Download Progress in Flutter with Firebase Storage
How to Start Programming: A Beginner's Guide
Single Device Login in Flutter Using Firebase Authentication and Firestore/Realtime Database
4 Ways to Close Keyboard in Flutter App