Exciting News! Our blog has a new Home! π
Background
The PageView widget allows user to transition between different screens in their Flutter application. As per Flutter doc,
PageView is a scrollable list that works page by page. Each child of a page view is forced to be the same size as the viewport.
Each child within a PageView
is typically constrained to the same size as the viewport, limiting flexibility in layout design. But what if we want our PageView
to dynamically adjust its size based on the content it contains?
In this article, weβll implement the PageView
with children of different heights to make it flexible.
What weβll achieve at the end of this blog?
You can find the full source code on GitHub.
Table of Content
- Background
- Let's get started
- Implement Adaptive PageView
- Implement SizeNotifier Widget
- Implement PageView using SizeNotifier
- Use Custom ThreePageScrollView
- Add PageContoller to PageView
- Add ThreePageScrollView to UI
- Enhance PageView Scrolling with FastPageViewScrollPhysics
- Conclusion
Let's get started
First, let's quickly have a look at the Pageview in Flutter, For simplicity, we have added a simple UI.
class StarterPageView extends StatelessWidget {
StarterPageView({super.key});
final List<int> items= List.generate(5, (index) => index);
@override
Widget build(BuildContext context) {
return SizedBox(
height: 400,
child: PageView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color:Colors.black,
),
child: Wrap(
children: List.generate(index+1, (index) {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.yellow,
),
height: 50,
child: ListTile(
title: Text('Page ${index+1}'),
),
);
}),
)
);
},
),
);
}
}
Here is the result,
The problem with the Pageview in Flutter is it canβt have dynamic height.
If we have a tab that might have a height of 100 px and another 200 px then it canβt adjust the height to the currently displayed page. ππ
Our goal? To create a PageView that adjusts its dimensions based on its content. So, Letβs start implementing it without wasting time.
Implement Adaptive PageView
We'll divide implementation into 5 simple steps to make each step easy to understand.
Implement SizeNotifier Widget
To implement dynamic sizing within our PageView, we'll start by implementing a widget that measures the size of the child and notifies the parent widget if the child's size is different than the previous one.
class SizeNotifierWidget extends StatefulWidget {
final Widget child;
final ValueChanged<Size> onSizeChange;
const SizeNotifierWidget({
super.key,
required this.child,
required this.onSizeChange,
});
@override
State<SizeNotifierWidget> createState() => _SizeNotifierWidgetState();
}
class _SizeNotifierWidgetState extends State<SizeNotifierWidget> {
Size? _oldSize;
@override
void didUpdateWidget(covariant SizeNotifierWidget oldWidget) {
WidgetsBinding.instance.addPostFrameCallback((_) => _notifySize());
super.didUpdateWidget(oldWidget);
}
@override
Widget build(BuildContext context) {
return widget.child;
}
void _notifySize() {
final size = context.size;
if (size != null && _oldSize != size) {
_oldSize = size;
widget.onSizeChange(size);
}
}
}
This widget is used to monitor the size of its child widget and trigger a callback whenever that size changes. Letβs break it down,
It takes two required parameters,
child
: The child widget that this SizeNotifierWidget will render.onSizeChange
: A callback function that will be invoked whenever the size of this widget changes.
Inside the didUpdateWidget()
Method,
This method is called whenever the widget is rebuilt with a different configuration.
Inside this method, a post-frame callback is added using
WidgetsBinding.instance.addPostFrameCallback()
. This callback ensures that_notifySize()
is called after the frame is rendered. This is necessary because the size of a widget is only available after it has been laid out on the screen.
Implement PageView using SizeNotifier
Now, weβll use this widget to measure the size of the current item in the PageView. So, whenever the child has a different height then it notifies about that.
class ThreePageScrollView extends StatefulWidget {
final Widget current;
const ThreePageScrollView({
super.key,
required this.current,
});
@override
State<ThreePageScrollView> createState() => _ThreePageScrollViewState();
}
class _ThreePageScrollViewState extends State<ThreePageScrollView> {
double? _currentItemHeight;
@override
Widget build(BuildContext context) {
return Stack(
children: [
Opacity(
opacity: 0,
child: SizeNotifierWidget(
child: widget.current,
onSizeChange: (size) {
setState(() {
_currentItemHeight = size.height;
});
},
),
),
SizedBox(
height: _currentItemHeight ?? 0,
child: PageView(
children: [
widget.current,
],
)),
],
);
}
}
The code is pretty simple, here we've used the SizeNotifier widget to measure the size of the current item and set that size to give it to PageView.
Let's add a simple UI to see if it's working or not.
Use Custom ThreePageScrollView
We'll add a simple UI to verify its functionality.
class FinalPageView extends StatelessWidget {
FinalPageView({super.key});
int itemCount = 1; // Number of items in the page view
@override
Widget build(BuildContext context) {
return ThreePageScrollView(
current: getItem(),
);
}
Widget getItem() {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.black,
),
child: Wrap(
children: List.generate(itemCount, (index) {
return Container(
margin: const EdgeInsets.all(10),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
color: Colors.yellow,
),
height: 50,
child: ListTile(
title: Text('Page ${index + 1}'),
),
);
}),
));
}
}
The code is pretty straightforward, we have used our Custom PageView and added a child from the getItem() function. Let's see what it looks like,
Ah, got it!!
Now, let's make it swipeable.π
Add PageController
to PageView
Weβll implement the PageViewController to manage PageView and to make it scrollable.
class ThreePageScrollView extends StatefulWidget {
final Widget current;
final Widget? next;
final Widget? previous;
final Function(int)? onPageChanged;
const ThreePageScrollView({
super.key,
required this.current,
this.next,
this.previous,
required this.onPageChanged,
});
@override
State<ThreePageScrollView> createState() => _ThreePageScrollViewState();
}
class _ThreePageScrollViewState extends State<ThreePageScrollView> {
late PageController _pageController;
double? _currentItemHeight;
late int currentPage;
@override
void initState() {
super.initState();
currentPage = widget.previous == null ? 0 : 1;
_pageController = PageController(initialPage: currentPage);
_pageController.addListener(() {
final newPage = _pageController.page?.toInt();
if (newPage == null || newPage.toDouble() != _pageController.page) return;
if (newPage == currentPage) {
return;
}
_pageController.jumpToPage(1);
widget.onPageChanged!(newPage > currentPage ? 1 : -1);
currentPage = 1;
});
}
@override
void didUpdateWidget(covariant ThreePageScrollView oldWidget) {
super.didUpdateWidget(oldWidget);
if (widget.previous != oldWidget.previous) {
final newPage = widget.previous == null ? 0 : 1;
if (newPage != currentPage) {
currentPage = newPage;
_pageController.jumpToPage(newPage);
}
}
}
@override
Widget build(BuildContext context) {
return Stack(
children: [
....
SizedBox(
height: _currentItemHeight ?? 0,
child: PageView(
controller: _pageController,
physics: const FastPageViewScrollPhysics(),
children: [
if (widget.previous != null) widget.previous!,
widget.current,
if (widget.next != null) widget.next!,
],
)),
],
);
}
}
Here we have-
Before implementing PageContoller
, it's essential to have the previous and next child other than the current one to make it scrollable. So, We have set the following parameters,
-
next
: A widget representing the next page. -
previous
: A widget representing the previous page. -
onPageChanged(int)
: A callback function that is invoked when the page changes. It receives an integer parameter indicating the direction of the change (-1 for the previous, 1 for the next).
Variables: _pageController
to manage PageView
and currentPage
variable is used to keep track of the current page index.
initState()
Method
- Sets the initial page based on whether previous is provided. If previous is null, set the current page to 0; otherwise, set it to 1.
- Adds a listener to
_pageController
to detect page changes. When the page changes, it callswidget.onPageChanged
with the direction of the change.
didUpdateWidget()
Method
It checks if previous has changed and updates the current page accordingly. If previous becomes null, it sets the current page to 0; otherwise, it sets it to 1.
To read the full version, please visit this blog.
Weβre Grateful to have you with us on this journey!
I encourage you to share your thoughts in the comments section below. Your input not only enriches our content but also fuels our motivation to create more valuable and informative articles for you.
Follow Canopas to get updates on interesting articles!
Top comments (1)
As I delve further into CapstoneProject.net, I'm continuously amazed by the wealth of resources tailored for amateur enthusiasts embarking on capstone projects: capstoneproject.net/. Each discovery I make adds a new dimension to my understanding and equips me with practical skills to navigate this dynamic field. The platform's intuitive interface facilitates seamless navigation, enabling me to explore diverse topics and refine my expertise effortlessly. With CapstoneProject.net as my trusted companion, I eagerly embrace the opportunities for growth and learning that lie ahead in the world of capstone projects.