How can i create an Carousel of Containers Like the example below?
I looked at Pageview class but this only displays one Container and hides the others. But i want to see the Container partly on the left and right too. Is there anyway to do this in Flutter and how?
Note: The current Container should always stay in the center
Edit: Darky gave an very good Example but i have one problem with his given code:
The following ArgumentError was thrown building AnimatedBuilder(animation: PageController#fc5f0(one client, offset 0.0), dirty, state: _AnimatedState#1ea5c): Invalid argument (lowerLimit): not a number: null –
This gets thrown at the Position where he calls controller.page. Does anyone know how i can fix this?
Actually what you want is PageView
.
PageView
accept a PageController
as argument. And that controller possess a viewportFraction
property (default to 1.0) which represent in percent the main-size of displayed pages.
Which means that with a viewportFraction of 0.5, the main page will be centered. And you'll see half a page on both left and right (if there's one)
Example :
class Carroussel extends StatefulWidget {
@override
_CarrousselState createState() => new _CarrousselState();
}
class _CarrousselState extends State<Carroussel> {
PageController controller;
int currentpage = 0;
@override
initState() {
super.initState();
controller = new PageController(
initialPage: currentpage,
keepPage: false,
viewportFraction: 0.5,
);
}
@override
dispose() {
controller.dispose();
super.dispose();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
body: new Center(
child: new Container(
child: new PageView.builder(
onPageChanged: (value) {
setState(() {
currentpage = value;
});
},
controller: controller,
itemBuilder: (context, index) => builder(index)),
),
),
);
}
builder(int index) {
return new AnimatedBuilder(
animation: controller,
builder: (context, child) {
double value = 1.0;
if (pageController.position.haveDimensions) {
value = controller.page - index;
value = (1 - (value.abs() * .5)).clamp(0.0, 1.0);
}
return new Center(
child: new SizedBox(
height: Curves.easeOut.transform(value) * 300,
width: Curves.easeOut.transform(value) * 250,
child: child,
),
);
},
child: new Container(
margin: const EdgeInsets.all(8.0),
color: index % 2 == 0 ? Colors.blue : Colors.red,
),
);
}
}
This solved my problem:
Future.delayed(const Duration(milliseconds: 20), () {
setState(() {
_pageController.animateToPage(0, duration: Duration(milliseconds: 1), curve: Curves.bounceIn);
});
});