Reputation: 615
Hi, I was trying to build a simple list in flutter with my custom constroller and a listener. Here is the code
class Test2 extends StatefulWidget {
@override
_Test2State createState() => _Test2State();
}
class _Test2State extends State<Test2> {
ScrollController scrollController = ScrollController();
@override
void initState() {
scrollController.addListener((){
print('controller called');
});
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
controller: scrollController,
itemCount: 8,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(
color: Colors.white,
height: 50,
),
);
},
));
}
}
My code works as intented but i'm trying to detect user swipes even when there is nothing to swipe. So far, if the list overflows the screen when user swipe scroll listener is called but, when the list of items is shorter than the screen size, this does not happend. How can i force listener to always listen?
Upvotes: 5
Views: 14089
Reputation: 628
Maybe this code can help you.
Wrapping the scaffold on a NotificationListener can listen all event,even itemCount is zero
Dont forget provide an AlwaysScrollableScrollPhysics physics object
import 'dart:math' as math;
import 'package:flutter/material.dart';
class TestPage extends StatefulWidget {
@override
_TestPageState createState() => _TestPageState();
}
class _TestPageState extends State<TestPage> {
@override
Widget build(BuildContext context) {
final ScrollController scrollController = ScrollController();
return NotificationListener(
child: Scaffold(
body: ListView.builder(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: 0,
itemBuilder: (context, index) {
return Container(
color: Colors.black,
height: 50,
);
},
),
),
onNotification: (notificationInfo) {
if (notificationInfo is ScrollStartNotification) {
print("scroll");
print("detail:"+notificationInfo.dragDetails.toString());
/// your code
}
return true;
},
);
}
}
Upvotes: 8
Reputation: 6186
You have to pass your custom scroll listener to the function as:
scrollController.addListener(_scrollListener);
Complete:
@override
void initState() {
scrollController.addListener(_scrollListener);
super.initState();
}
and your custom scroll listener method:
_scrollListener() {
if (_controller.offset >= _controller.position.maxScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the bottom";
});
}
if (_controller.offset <= _controller.position.minScrollExtent &&
!_controller.position.outOfRange) {
setState(() {
message = "reach the top";
});
}
}
Upvotes: 3