Flutter AlwaysScrollableScrollPhysics() not working - flutter

Question
Hi, I was searching a solution to allow user scroll on a list even when there is insufficient content.
Looking throght Flutter documentation i found this page https://api.flutter.dev/flutter/widgets/ScrollView/physics.html
As the documentation said
To force the scroll view to always be scrollable even if there is insufficient content, as if primary was true but without necessarily setting it to true, provide an AlwaysScrollableScrollPhysics physics object, as in:
physics: const AlwaysScrollableScrollPhysics(),
so I tried to run a simple code an detect user scroll even when there isn't enough content
code
class Page extends StatefulWidget {
#override
_PageState createState() => _PageState();
}
class _PageState extends State<Page> {
#override
Widget build(BuildContext context) {
final ScrollController scrollController = ScrollController();
#override
void initState(){
scrollController.addListener((){
print('listener called');
});
super.initState();
}
return Scaffold(
body: ListView.builder(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (context, index){
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Container(
color: Colors.black,
height: 50,
),
);
},
),
);
}
}
Why this isn't working?
edit
Here is the design i'm looking forward
I have a list that is dynamically created. I want to be able to detect user vertical swipes on that list even if there is no scroll because there aren't enough element to overflow the screen height.
On a scrollable list I can simply add a scroll Listener and then every time a scroll is detected I can do my logic with scrollController.position info's.
I want scroll listener to be called even when user swipes on list of this type

I do see the effect of scroll with the addition of AlwaysScrollableScrollPhysics so that part seems to be working. Maybe wrapping the scaffold on a NotificationListener can do what you're trying to do:
class _PageState extends State<Page> {
#override
Widget build(BuildContext context) {
final ScrollController scrollController = ScrollController();
return NotificationListener(
child: Scaffold(
body: ListView.builder(
controller: scrollController,
physics: const AlwaysScrollableScrollPhysics(),
itemCount: 5,
itemBuilder: (context, index) {
return Padding(
padding: const EdgeInsets.only(bottom: 8.0),
child: Container(
color: Colors.black,
height: 50,
),
);
},
),
),
onNotification: (scrollNotification) {
if (scrollNotification is ScrollStartNotification) {
print('Widget has started scrolling');
}
return true;
},
);
}
}
NotificationListener has a property called onNotification that allows you to check for different kinds of scrollNotifications, you can check more here: NotificationListener Class and ScrollNotification class

Related

My `GridView` breaks or is not scrollable

I am pulling my hair trying to make my grid view displays within the user's profile page, which is basically a Column Widget.
Either I get error regarding the "unbounceness" of the widget or other error like RenderFlex children have non-zero flex but incoming height constraints are unbounded..
If I set the shrinkWrap to true the grid is there, but unscrollable.
I tried many solution such as adding a Flexible or Expanded parent with a mainAxisSize to min for the Column.
My grid view code is a as follows:
/// A grid view of the user's ads
class UserAdWidget extends StatelessWidget {
final String userId;
const UserAdWidget({super.key, required this.userId});
#override
Widget build(BuildContext context) {
final query = ClassifiedAd.getQueryFromUserId(userId);
return FirestoreQueryBuilder<ClassifiedAd>(
query: query,
builder: (context, snapshot, _) => Flexible(
child: GridView.builder(
shrinkWrap: true,
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 200,
crossAxisSpacing: 2,
mainAxisSpacing: 20),
itemCount: snapshot.docs.length,
itemBuilder: (context, index) {
// if we reached the end of the current items, get more
if (snapshot.hasMore && index + 1 == snapshot.docs.length) {
snapshot.fetchMore();
}
final ad = snapshot.docs[index].data();
return ad.galleryWidget(context,
withAvatar: false, onTap: () {});
})));
}
}
The component code where the grid is rendered within a Column is as follows:
#override
Widget build(BuildContext context) {
return Consumer<StateModel>(builder: (context, appState, child) {
final selfProfile = appState.loggedUser?.id == widget.user.id;
return Scaffold(
appBar: AppBar(
title:
Text(selfProfile ? "Votre profil" : widget.user.displayName)),
body: SingleChildScrollView(
physics: const BouncingScrollPhysics(),
child: Column(mainAxisSize: MainAxisSize.min, children: [
// === User's profile widget
UserProfileWidget(user: widget.user),
const Divider(),
// == Grid of user's ads
const Text("The ads:"),
const Text(""),
UserAdWidget(userId: widget.user.id),
])));
});
}
The current code renders like so but does not scroll:

PageView, inside ListView, inside Column: `Null check operator used on a null value`

I have a PageView, inside a ListView, inside a Column. It seems necessary because of the layout (top green widget should be scrollable, but bottom widget shouldn't be).
class MyWidget extends StatefulWidget {
Widget createPage(int page, Color color) {
return Container(
color: color,
child: Padding(
padding: EdgeInsets.symmetric(vertical: 200.0),
child: Text("Page: $page. Swipe right to go to next page"),
),
);
}
late final List<Widget> pages = [
createPage(1, Colors.purple),
createPage(2, Colors.red)
];
#override
createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
late final PageController _pageController;
int page = 0;
#override
initState() {
super.initState();
_pageController = PageController();
}
#override
Widget build(BuildContext context) {
return Column(
children: [
Expanded(
child: ListView(
children: [
Container(
color: Colors.green,
child: const Text("Top of screen, scrollable.")),
// This works
Column(
children: widget.pages,
),
// PageView tries to take the full height. Without Flexible, PageView is unbounded.
// Flexible(
// child: PageView.builder(
// itemCount: widget.pages.length,
// controller: _pageController,
// onPageChanged: (int index) => setState(() => page = index),
// itemBuilder: (context, index) => widget.pages[index],
// ),
// )
],
),
),
Container(
color: Colors.green, child: const Text("Bottom of screen, always")),
],
);
}
}
However, I get various error based on what I try. This is an unhelpful error, since ListView doesn't have a problem when it's children is a Column:
The following _CastError was thrown during performLayout():
Null check operator used on a null value
The relevant error-causing widget was:
ListView ListView:file:///path/to/project/lib/main.dart:63:18
Code
I've created a Dartpad pad to reproduce this. I've commented out the PageView and replaced it with a column so you can see the app. The issue is replacing Column with 2 pages to PageView.
I've tried various things:
Wrapping ListView in things:
SizedBox.expand(child: ListView(...))
Expanded(child: ListView(...)) following this answer
Flexible(child: ListView(...))
ListView.builder(shrinkWrap: true,...),
Changing mainAxisSize of Column

Flutter: ListView - Green overlay instead of arrows in widget inspector

I'm creating a ListView with a builder function. I use the widget inspector to assess the any issues with the layout of the widgets.
Usually, the listView shows downwards green arrows as shown here:
[ListView layout][1]
However, in my current app, whenever I create a listView, it shows this green overlay on the listView. This creates artefacts with Image widget nested in stack; the images flicker when scrolling. [artefact layout][2]
This layout does look like it will take the space of 'drawer' in scaffold however, this page does not have a drawer, although all the other pages do.
Please find the code below for your reference.
const BlogListPage({Key? key}) : super(key: key);
#override
State<BlogListPage> createState() => _BlogListPageState();
}
class _BlogListPageState extends State<BlogListPage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: ASAppBar(
title: const Text('Blogs'),
),
body: ListView.builder(
itemCount: 10,
itemBuilder: (BuildContext context, int index) {
return Container(
margin:
const EdgeInsets.symmetric(vertical: 16.0, horizontal: 24.0),
color: Colors.amber,
child: const SizedBox(
height: 100,
width: double.infinity,
),
);
},
));
}
} ```
[1]: https://i.stack.imgur.com/O7Pnc.png
[2]: https://i.stack.imgur.com/0g5HF.png

PageView rebuilding while animateToPage is in progress

I'm creating a social media feed where each post is an image of a different size. The user can swipe right to like, left to dislike, up to skip to the next post, or down to go back. To do that, I'm using a Dismissible widget within a PageView, where each page contains a post/image. I used "animateToPage" in the Dismissible to automatically animate to the next page once the user swipes right or left.
The problem is that when the PageView animates to the next page, the image that was dismissed suddenly reappears on the previous page while the animation is happening. I want it to reappear only if the user swipes down to go back to the previous post, but not while the PageView is animating.
Here's a video showing what is going wrong
And here's an animation showing what I need
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> with TickerProviderStateMixin{
int pageIndex = 0;
PageController _pageController = PageController(
initialPage: 0,
);
#override
Widget build(BuildContext context) {
List images = [
'assets/1.jpg', 'assets/2.jpg', 'assets/3.jpg', 'assets/4.jpg', 'assets/5.jpg',
];
return MaterialApp(
home: Scaffold(
backgroundColor: Color.fromRGBO(250, 250, 250, 1),
body: LayoutBuilder(
builder: (context, constraints) => PageView.builder(
controller: _pageController,
itemCount: 5,
scrollDirection: Axis.vertical,
itemBuilder: (context, index) {
return images.map((image) => Dismissible(
onResize: () {
setState(() {
_pageController.animateToPage(index+1, duration: Duration(milliseconds: 300), curve: Curves.ease);
});
},
onDismissed: (direction) {},
key: UniqueKey(),
child: Container(
padding: const EdgeInsets.all(20.0),
child: Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 100),
child: Container(
alignment: Alignment.center,
child: Image(
image: AssetImage(image)
),
),
),
),
),
))
.toList()[index];
}
),
),
),
);
}
}
I assume this is happening because PageView is rebuilding the other pages while the animation is in progress. I'm still a beginner in Flutter and wasn't able to find a solution. Any ideas of how to fix this?
Everytime setState is called, the widget is redrawn. Try to put your animated code outside of setState method.
Documentation

Flutter How to remove overscroll effect from ListView [duplicate]

By default, flutter adds a glowing effect on ListView/GridView/... to overscrolls on android phones
I would like to remove this effect entirely or on one specific scrollable.
I know that I can change ScrollPhysics to change between Bounce/Clamp. But this doesn't actually remove the glow effect.
What can I do ?
The glow effect comes from GlowingOverscrollIndicator added by ScrollBehavior
To remove this effect, you need to specify a custom ScrollBehavior. For that, simply wrap any given part of your application into a ScrollConfiguration with the desired ScrollBehavior.
The following ScrollBehavior will remove the glow effect entirely :
class MyBehavior extends ScrollBehavior {
#override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
To remove the glow on the whole application, you can add it right under MaterialApp :
MaterialApp(
builder: (context, child) {
return ScrollConfiguration(
behavior: MyBehavior(),
child: child,
);
},
home: new MyHomePage(),
);
To remove it on a specific ListView, instead wrap only the desired ListView :
ScrollConfiguration(
behavior: MyBehavior(),
child: ListView(
...
),
)
This is also valid if you want to change the effect. Like adding a fade when reaching borders of the scroll view.
The glow will disappear by changing the ListView's physics property to BouncingScrollPhysics to imitate the List behavior on iOS.
ListView.builder(
physics: BouncingScrollPhysics(),
}
The above solution did not work for me. I did this from another solution.
Wrap it with this widget to remove the shadow completely:
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (overscroll) {
overscroll.disallowGlow();
},
child: new ListView.builder(
//Your stuff here.
),
),
You can try BouncingScrollPhysics with all list or grid or scrollview:
//ScrollView:
SingleChildScrollView(
physics: BouncingScrollPhysics(),
)
//For ListView:
ListView.builder(
physics: BouncingScrollPhysics(),
}
//GridView
GridView.Builder(
physics: BouncingScrollPhysics(),
)
You can wrap your SingleChildScrollView or ListView.
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification overscroll) {
overscroll.disallowGlow();
return;
},
child: SingleChildScrollView()
)
Update on 2021
as buildViewportChrome is deprecated on March `21, we may have new way to implement this
A. Working Solution
class MyCustomScrollBehavior extends MaterialScrollBehavior {
#override
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
class MainApp extends StatelessWidget {
const MainApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
scrollBehavior: MyCustomScrollBehavior(),
title: 'App Title',
home: HomeUI(),
);
}
}
B. Explanation
By default, Flutter wraps any child widget into GlowingOverscrollIndicator as below code.
#override
Widget buildOverscrollIndicator(BuildContext context, Widget child, ScrollableDetails details) {
switch (getPlatform(context)) {
case TargetPlatform.iOS:
case TargetPlatform.linux:
case TargetPlatform.macOS:
case TargetPlatform.windows:
return child;
case TargetPlatform.android:
case TargetPlatform.fuchsia:
return GlowingOverscrollIndicator(
axisDirection: details.direction,
color: Theme.of(context).colorScheme.secondary,
child: child, // < ---------- our Child Widget is wrapped by Glowing Indicator
);
}
}
So we can easily override it, by directly return child without wrapping it to GlowingOverscrollIndicator
class MyCustomScrollBehavior extends MaterialScrollBehavior {
#override
Widget buildOverscrollIndicator(
BuildContext context, Widget child, ScrollableDetails details) {
return child;
}
}
You don't need to build your own custom ScrollBehavior class. Instead, just wrap your scrollable widget in a ScrollConfiguration widget and set the behavior property to:
const ScrollBehavior().copyWith(overscroll: false).
Full code example:
ScrollConfiguration(
behavior: const ScrollBehavior().copyWith(overscroll: false),
child: PageView(
physics: const PageScrollPhysics(),
controller: model.pageController,
children: [
PageOne(),
PageTwo(),
PageThree(),
PageFour(),
],
),
),
try this work for me mybe work for you to
ScrollConfiguration(
behavior: new ScrollBehavior()..buildViewportChrome(context, null, AxisDirection.down),
child: SingleChildScrollView()
);
You can also try
SingleChildScrollView(
physics: ClampingScrollPhysics(),
)
If you migrated to null safety, you might get issues with the behavior. You can use this method that works with null safety:
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (OverscrollIndicatorNotification? overscroll) {
overscroll!.disallowGlow();
return true;
},
child: child,
),
The currently accepted answer is outdated in the current version of Flutter.
Scroll behavior's ScrollBehavior.copyWith() method has an overscroll flag which can be set to false to avoid having to create your own ScrollBehavior class.
For example:
ScrollConfiguration(
behavior: MaterialScrollBehavior().copyWith(overscroll: false),
child : someScrollableWidget
)
`
It isn't good practice to just change the scroll behavior, as you may lose the native scrolling feel when running your app on different devices.
I have used below one for Scroll body without Scroll glow effect
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ScrollConfiguration(
behavior: new ScrollBehavior()
..buildViewportChrome(context, null, AxisDirection.down),
child: SingleChildScrollView(
After Flutter 2.10 update Previous NotificationListener parameter code has been removed/deprecated.
New Code
NotificationListener<OverscrollIndicatorNotification>(
onNotification: (overscroll) {
overscroll.disallowIndicator(); //previous code overscroll.disallowGlow();
return true;
},
child: ListView(
padding: const EdgeInsets.symmetric(
horizontal: 15, vertical: 15),
scrollDirection: Axis.horizontal,
children: List.generate(
items.length,
(index) => Padding(
padding: const EdgeInsets.only(right: 15),
child: AspectRatio(
aspectRatio: 13 / 9,
child:
LayoutBuilder(builder: (context, boxcon) {
return Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
boxShadow: const [
BoxShadow(
color: Colors.black12,
spreadRadius: 5,
blurRadius: 12)
],
image: DecorationImage(
fit: BoxFit.cover,
image: NetworkImage(items[index])),
color: greengradientcolor,
),
);
}),
))),
),
),