How can i smoothly scroll between NestedScrollView and ListView.builder - flutter

I have the following simple full code ..
import 'package:flutter/material.dart';
class Profile extends StatefulWidget {
const Profile({ Key? key, }) : super(key: key);
#override
ProfileState createState() => ProfileState();
}
class ProfileState extends State<Profile>{
#override
Widget build(BuildContext context) {
return SafeArea(
child: NestedScrollView(
headerSliverBuilder: (context,value){
return[
const SliverAppBar(
expandedHeight: 400,
)
];
},
body: ListView.builder(
itemCount: 200,
itemBuilder: (BuildContext context, int index) {
return Center(child: Text(index.toString()));
},
)
),
);
}
}
in the previous code, everything is ok and it shifted the scroll in a smooth way BUT when I provide ScrollController into my ListView.builder the scroll is no longer smooth anymore.
so Please How could I keep the first result (with no providing ScrollController) the same as (with providing ScrollController)? .

I recreated your requirements using CustomScrollView, the API is "harder" to use but it allows you implement more complex features (like nested scrollviews as you are doing) because we have direct access to the Slivers API.
You can see that almost any Flutter scrollable widget is a derivation of either CustomScrollView or ScrollView which makes use of Slivers.
NestedScrollView is a subclass of CustomScrollView.
ListView and GridView widgets are subclasses of ScrollView.
Although seems complicated a Sliver is just a portion of a scrollable area:
CustomScrollView(
controller: _scrollController,
slivers: [
const SliverAppBar(expandedHeight: 400),
SliverList(
delegate: SliverChildBuilderDelegate(
(context, index) {
return Center(child: Text('item $index.'));
},
),
),
],
)
So, instead of creating multiple scrollviews and trying to mix them together (which lead to buggy behaviors), just declare multiple scrollable areas and put them together inside a CustomScrollView, that's it.
See the working example at: https://dartpad.dev/?id=60cb0fa073975f3c80660815ae88af4e.

Related

Flutter - Not able to scroll Listview

I'm trying to write basic Listview example, however not able to scroll down, screen is fixed not able to view all items.
Tried with working example from flutter official documentation (displaying Listview till items29) https://api.flutter.dev/flutter/widgets/ListView-class.html
Not able to figure out Whether it is settings issue or other.
import 'package:flutter/material.dart';
class mySquare extends StatelessWidget {
String child;
mySquare({required this.child});
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(8.0),
child: Container(height: 200, color: Colors.amber, child: Text(child)),
);
}
}
class HomePage extends StatelessWidget {
List posts = ['post1', 'post2', 'post3', 'post4', 'post5', 'post6'];
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
itemCount: posts.length,
itemBuilder: ((BuildContext context, index) {
return mySquare(
child: posts[index],
);
}),
),
);
}
}
I launched your code on Android emulator and it works as expected.
If the device is big enough for all items ListView wouldn't scroll

Flutter - Using Dismissible on a PageView creates an ugly animation

with the following example code, is get a very ugly animation.
I would even say, it's no animation at all.
The next Page will just appear after the setstate is called.
How can I create a smooth delete animation using PageView?
If it is not possible via PageView, is there any alternative, that has the "snapping cards" feature?
Here is my code:
class SwipeScreen extends StatefulWidget {
const SwipeScreen({Key key}) : super(key: key);
static const routeName = '/swipe';
#override
_SwipeScreenState createState() => _SwipeScreenState();
}
class _SwipeScreenState extends State<SwipeScreen> {
List<String> content = ['one', 'two', 'three', 'four', 'five'];
#override
Widget build(BuildContext context) {
return Scaffold(
body: PageView.builder(
scrollDirection: Axis.vertical,
itemCount: content.length,
controller: PageController(viewportFraction: 0.8),
itemBuilder: (context, index) {
return Dismissible(
key: ValueKey(content[index]),
child: Card(
child: Container(
height: MediaQuery.of(context).size.height * 0.8,
child: Text('test'),
),
),
onDismissed: (direction) {
setState(() {
content = List.from(content)..removeAt(index);
});
},
);
},
),
);
}
}
Replacing PageView.builder() with ListView.builder() will create a smoother animation.
Hopefully this is what you're looking for!
Unfortunately, the PageView widget is not intended to be used with the Dismissible widget as the animation when the dismiss is complete is not implemented.
You can still change your PageView to a ListView and set a physics to PageScrollPhysics() to get the animation on dismiss but you will probably encounter some other issues on Widget sizes

How to trigger a function call when sliver child is in the center of the screen?

I have a sliver list in a custom scroll view.
Each child in the sliver list has a dynamic height. I want to trigger a function call in my viewmodel whenever one of the child widgets is crossing the center point of the screen view.
As shown below, I am using MVVM (FilledStack's architecture) which uses the ViewModelProvider to link the view to a viewmodel. This is generating a list of "Post Cards" views.
class HomeView extends StatelessWidget {
#override
Widget build(BuildContext context) {
return ViewModelProvider<HomeViewModel>.withConsumer(
viewModel: HomeViewModel(),
onModelReady: (model) => model.initialise(),
builder: (BuildContext context, HomeViewModel model, Widget child) =>
SafeArea(
child: Scaffold(
bottomNavigationBar: _buildBottomAppBar(model),
body: CustomScrollView(
controller: model.scrollController,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int postIndex) => PostCard(
postIndex: postIndex,
),
childCount: model.posts?.length,
),
),
],
);
),
),
);
}
I tried global key inside of the PostCard:
GlobalKey _postKey = GlobalKey();
#override
void initState() {
WidgetsBinding.instance.addPostFrameCallback(_afterLayout);
super.initState();
}
This calls a _afterLayout function after the item is rendered. This required me to change it to a stateful widget for the init state and it works to print the location but it feels very much like a hack.
Is there a cleaner way to get the position and size of each child of a sliver list?
I solved this by creating my own CustomSliverList and CustomRenderSliverList.
In the CustomRenderSliverList's performLayout() function you can use the constraints.scrollOffset and constraints.remainingPaintExtent to get the current view port and then using the child RenderBox object to figure out position and size of each child.
From that you can use a callback function to perform any action when it enters the view port.

How to create infinity PageView in Flutter

How to create an PageView which are supported circle scroll in Flutter? That's mean when I stand on 0 page, I could scroll to left to the last page.
Updated: I answered this question and update a gist source also.
What I did with mine was I set my page controller's initialPage to 10000 * pageCount, and in my page view itself, I have itemBuilder: (context, index) => pages[index % pageCount], and itemCount: null. It's not really infinite, but most users will not scroll 10000 pages back, so it works for my use case. As far as I know, there isn't an elegant way to make it truly infinite. You could probably set up a listener so that whenever the controller.page is about to become 0, you set it back to 10000 * pageCount or something similar.
I found a solution here. I create a CustomScrollView with 2 slivers. One for go forward, one for go back. However, I have to calculate if my list short.
typedef Widget Builder(BuildContext buildContext, int index);
class InfiniteScrollView extends StatefulWidget {
final Key center = UniqueKey();
final Builder builder;
final int childCount;
InfiniteScrollView(
{Key key, #required this.builder, #required this.childCount})
: super(key: key);
#override
_InfiniteScrollViewState createState() => _InfiniteScrollViewState();
}
class _InfiniteScrollViewState extends State<InfiniteScrollView> {
#override
Widget build(BuildContext context) {
return Container(
child: CustomScrollView(
center: widget.center,
scrollDirection: Axis.horizontal,
slivers: <Widget>[
SliverList(
delegate: SliverChildBuilderDelegate(
(BuildContext context, int index) => widget.builder(
context, widget.childCount - index % widget.childCount - 1),
),
),
SliverList(
delegate: SliverChildBuilderDelegate(widget.builder),
key: widget.center,
)
],
),
);
}
}
Updated: I write a new widget which support infinity TabBar.
https://gist.github.com/MrNinja/6f6a5fc73803bdfaf2a493a35c258fee

Animating changes in a SliverList

I currently have a SliverList whose items are loaded dynamically. The issue is that once these items are loaded, the SliverList updates without animating the changes, making the transition between loading & loaded very jarring.
I see that AnimatedList exists but it isn't a sliver so I can't place it directly in a CustomScrollView.
You probably know about this now, but might as well mention it here to help people.
You can use SliverAnimatedList. It achieves the required result.
SliverAnimatedList Construction:
itemBuilder defines the way new items are built. The builder should typically return a Transition widget, or any widget that would use the animation parameter.
SliverAnimatedList(
key: someKey,
initialItemCount: itemCount,
itemBuilder: (context, index, animation) => SizeTransition(
sizeFactor: animation,
child: SomeWidget()
)
)
Adding/removing dynamically
You do that by using insertItem and removeItem methods of SliverAnimatedListState. You access the state by either:
providing a Key to the SliverAnimatedList and use key.currentState
using SliverAnimatedList.of(context) static method.
In cases where you need to make changes from outside of the list, you're always going to need to use the key.
Here's a full example to clarify things. Items are added by tapping the FloatingActionButton and are removed by tapping the item itself. I used both the key and of(context) ways to access the SliverAnimatedListState.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SliverAnimatedListTest extends StatefulWidget {
#override
_SliverAnimatedListTestState createState() => _SliverAnimatedListTestState();
}
class _SliverAnimatedListTestState extends State<SliverAnimatedListTest> {
int itemCount = 2;
// The key to be used when accessing SliverAnimatedListState
final GlobalKey<SliverAnimatedListState> _listKey =
GlobalKey<SliverAnimatedListState>();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Sliver Animated List Test")),
// fab will handle inserting a new item at the last index of the list.
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
_listKey.currentState.insertItem(itemCount);
itemCount++;
},
),
body: CustomScrollView(
slivers: <Widget>[
SliverAnimatedList(
key: _listKey,
initialItemCount: itemCount,
// Return a widget that is wrapped with a transition
itemBuilder: (context, index, animation) =>
SizeTransition(
sizeFactor: animation,
child: SomeWidget(
index: index,
// Handle removing an item using of(context) static method.
// Returned widget should also utilize the [animation] param
onPressed: () {
SliverAnimatedList.of(context).removeItem(
index,
(context, animation) => SizeTransition(
sizeFactor: animation,
child: SomeWidget(
index: index,
)));
itemCount--;
}),
))
],
),
);
}
}
class SomeWidget extends StatelessWidget {
final int index;
final Function() onPressed;
const SomeWidget({Key key, this.index, this.onPressed}) : super(key: key);
#override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: FlatButton(
child: Text("item $index"),
onPressed: onPressed,
)));
}
}
You can use Implicitly Animated Reorderable List
import 'package:implicitly_animated_reorderable_list/implicitly_animated_reorderable_list.dart';
import 'package:implicitly_animated_reorderable_list/transitions.dart';
...
SliverImplicitlyAnimatedList<Comment>(
items: comments,
areItemsTheSame: (a, b) => a.id == b.id,
itemBuilder: (BuildContext context, Animation<double> animation, Comment item, int index) {
return SizeFadeTransition(
sizeFraction: 0.7,
curve: Curves.easeInOut,
animation: animation,
child: CommentSliver(
comment: item,
),
);
},
);
I have a workaround for using a simple ListView with a Sliver. It's not perfect and it has limitations, but it works for the case where you just have 2 Slivers, the AppBar and a SliverList.
NestedScrollView(
headerSliverBuilder: (_, _a) => SliverAppBar(<Insert Code Here>),
body: MediaQuery.removePadding(
removeTop: true,
context: context,
child: AnimatedList(
<InsertCodeHere>
)))
You can tweak around with the Widget tree, but that's the basic idea. Wrap the sliver appbar in a NestedScrollView and place the List in the body.
You could Wrap your list items in an AnimatedWidget
Read about it in the docs AnimatedWidget