A Viewpager allows to view the pages of an application by scrolling horizontally or vertically
It is of use when displaying a sequence or pages like a carousel
infinite_view_pager
package provides InfiniteViewPager
component to be used to implement a view pager
It supports horizontal and vertical scroll
Check Flutter installation to setup Flutter
Use flutter create
command to create a Flutter project (here viewpager_app) :
flutter create viewpager_app
Add infinite_view_pager
package to pubspec.yaml
dependencies:
infinite_view_pager: "0.3.11"
flutter:
sdk: flutter
Run following command to add dependency
flutter pub get
import 'package:infinite_view_pager/infinite_view_pager.dart';
Create InfiniteViewPager
component with a pageBuilder
Widget which returns a page (Widget) for a particular index
Widget _buildPage(BuildContext context, int direction) {
return Container(
padding: EdgeInsets.all(60.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
elevation: 10,
child: Center(
child: Text(
(index + direction).toString(),
style: Theme.of(context).textTheme.display4,
),
),
),
);
}
Widget getViewPager() {
return InfiniteViewPager(
onPageChanged: (direction) {
index += direction;
},
pageBuilder: _buildPage,
scrollDirection: Axis.horizontal,
);
}
import 'package:flutter/material.dart';
import 'package:infinite_view_pager/infinite_view_pager.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter View Pager Example',
home: ViewPager(),
);
}
}
class ViewPager extends StatefulWidget {
@override
_ViewPagerState createState() => _ViewPagerState();
}
class _ViewPagerState extends State<ViewPager> {
int index = 0;
Widget _buildPage(BuildContext context, int direction) {
return Container(
padding: EdgeInsets.all(60.0),
child: Card(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(20.0),
),
elevation: 10,
child: Center(
child: Text(
(index + direction).toString(),
style: Theme.of(context).textTheme.display4,
),
),
),
);
}
@override
Widget build(BuildContext context) {
return Container(
child: InfiniteViewPager(
onPageChanged: (direction) {
index += direction;
},
pageBuilder: _buildPage,
scrollDirection: Axis.horizontal,
),
);
}
}
Ensure a supported device is connected or emulator/simulator is started
Go to project directory
Use flutter run
command to run
flutter run
It builds and runs app on an available android/ios device