I'm very new to flutter and I'm trying to learn how to create views. I tried to create a separate file of the view, or widget if that's what it's called in flutter, and just call it from the main.dart.
I have a separate widget containing this code
class PageEntryWidgetMain extends StatefulWidget {
final PageViewEntryMain pageViewEntryMain;
const PageEntryWidgetMain({Key key, this.pageViewEntryMain})
: super(key: key);
@override
State<StatefulWidget> createState() {
return _PageEntryWidgetMainState();
}
}
class _PageEntryWidgetMainState extends State<PageEntryWidgetMain> {
@override
Widget build(BuildContext context) {
return Container(
child: Row(
children: <Widget>[
Text(widget.pageViewEntryMain.title)
],
),
);
}
}
and I'm trying to show it by using a view pager with the following code
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
PageView.builder(
itemBuilder: (context, position) {
PageEntryWidgetMain(
pageViewEntryMain: pages[position],
);
},
itemCount: pages.length,
scrollDirection: Axis.horizontal,
)
],
),
),
);
but it gives me the following errors
I'm a little confused at what it's actually complaining of. I am able to display just one view, by replacing the PageView.builder with this code
PageEntryWidgetMain(pageViewEntryMain: pages[0])
So I believe that the separate widget, in itself, does not have a problem. It's probably about how I am trying to use the ViewPager that's giving me errors.
I have been searching for PageView implementations but I have not seen one that actually has a separate view to just call for displaying. I need to learn it this way so I would be able to separate the views instead of just writing it all in one file.
PageView
cannot be the direct child of Column
. Change your column to add an Expanded
between the two, as below:
Column(
children: <Widget>[
Expanded(
child: PageView.builder(),
),
]
)
To explain what's going on here, Column
has an unbounded horizontal width, ie it'll keep expanding horizontally to take as much space as it's child needs. PageView
(and any other horizontally scrolling widget) requires horizontal constraints for the scroll logic to work.
Expanded
restricts the horizontal size of the PageView
by taking up as much space as possible, which should solve the issue.
You can use any Widget that has a fixed height and width to wrap the PageView.
For example, I use Container()
:
Column(
children: <Widget>[
Container(
width: double.infinity,
height: 100.0,
child: PageView.builder(),
),
]
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With