How can I get Flutter to scroll with mouse drag instead of scroll wheel? (Linux)

Issue

I want to be able to use the mouse to drag / swipe the screen instead of using the scroll wheel. I’m running on Pop! OS 22.04 (Ubuntu Linux). Any help appreciated 🙂

Solution

Just add the snippet below to enable mouse dragging scroll and create it in the MaterialApp.scrollBehavior property:

// Enable scrolling with mouse dragging
class MyCustomScrollBehavior extends MaterialScrollBehavior {
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
      };
}

Check the live demo on DartPad and below the source code as a minimal-reproducible-example

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        //
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
      scrollBehavior: MyCustomScrollBehavior(), // <- Here
    );
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    //
    return Scaffold(
      body: Center(
        child: ListView.separated(
          itemBuilder: ((context, index) =>
              ListTile(title: Text('Item $index'))),
          separatorBuilder: (context, index) => const Divider(),
          itemCount: 100,
        ),
      ),
    );
  }
}

// Enable scrolling with mouse dragging
class MyCustomScrollBehavior extends MaterialScrollBehavior {
  @override
  Set<PointerDeviceKind> get dragDevices => {
        PointerDeviceKind.touch,
        PointerDeviceKind.mouse,
      };
}

Answered By – lepsch

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published