I want to constantly check if scrolling is not possible.
@override
void initState() {
super.initState();
WidgetsBinding.instance!.addPostFrameCallback((duration) {
print("${_scrollViewController.position.maxScrollExtent}");
// prints true if scrollable else false
print("isScrollable = ${_scrollViewController.position.maxScrollExtent != 0}");
});
}
I've tried this code, but it's only detected once and not continuously. What should I do?
CodePudding user response:
Use NotificationListener
widget.
example:
NotificationListener<ScrollNotification>(
child: ListView(
children: MyListChilren()),
onNotification: (ScrollNotification scrollNotif) {
print(scrollNotif.metrics.maxScrollExtent);
},
);
CodePudding user response:
I implemented what you want by adding 'addPostFrameCallback' to inside of 'build' method like below.
You can check print log by clicking floating button in this example code.
The floating button toggles 'Container' height for changing ListView scrollable or not scrollable.
Whenever called 'build' method, 'addPostFrameCallback' callback is called after rebuild and check whether scroll is scrollable.
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
ScrollController _scrollController = ScrollController();
double hhhh = 30;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
WidgetsBinding.instance.addPostFrameCallback((duration) {
print("${_scrollController.position.maxScrollExtent}");
// prints true if scrollable else false
print(
"isScrollable = ${_scrollController.position.maxScrollExtent != 0}");
});
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: _buildBody(),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
if (hhhh == 30) {
hhhh = 3333;
} else {
hhhh = 30;
}
});
},
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
Widget _buildBody() {
return ListView(
controller: _scrollController,
children: [
Container(height: hhhh, child: Text('a')),
Container(height: 30, child: Text('a')),
Container(height: 30, child: Text('a')),
Container(height: 30, child: Text('a')),
],
);
}
}