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:
GestureDetector
to detect horizontal drag gestures.onHorizontalDragUpdate
callback is triggered when the user drags horizontally.ListView
based on the drag distance using the jumpTo
method of the ScrollController
.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.