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

Time:07-17

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 :)

CodePudding user response:

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,
      };
}
  • Related