Skip to content

Instantly share code, notes, and snippets.

@BarryDaBee
Created December 17, 2021 16:42
Show Gist options
  • Select an option

  • Save BarryDaBee/1c2865d14f7fef91b7dd377fbfb49f10 to your computer and use it in GitHub Desktop.

Select an option

Save BarryDaBee/1c2865d14f7fef91b7dd377fbfb49f10 to your computer and use it in GitHub Desktop.
Implementation of automatic onboarding process using Timer and PageView in Flutter
import 'dart:async';
import 'package:flutter/material.dart';
class OnboardingView extends StatefulWidget {
const OnboardingView({Key? key}) : super(key: key);
@override
State<OnboardingView> createState() => _OnboardingViewState();
}
class _OnboardingViewState extends State<OnboardingView> {
final PageController _pageController = PageController();
late final Timer _timer;
int _currentPage = 0;
@override
void initState() {
_timer = Timer.periodic(const Duration(seconds: 1), (timer) {
_pageController.animateToPage(_pageController.page!.toInt() + 1,
duration: const Duration(milliseconds: 500), curve: Curves.easeIn);
if (_pageController.page!.toInt() >= 2) {
timer.cancel();
}
});
// _pageController.addListener((){
// setState((){})
// });
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Padding(
padding: const EdgeInsets.symmetric(horizontal: 50, vertical: 70),
child: Column(
children: [
Expanded(
child: PageView(
controller: _pageController,
onPageChanged: (int index) {
setState(() {
_currentPage = index;
});
},
children: const [
TestPage(
id: 0,
color: Colors.red,
text: 'This is page 0',
),
TestPage(
id: 1,
color: Colors.green,
text: 'This is page 1',
),
TestPage(
id: 2,
color: Colors.blue,
text: 'This is page 2',
),
],
),
),
Align(
alignment: Alignment.center,
child: CustomIndicator(
noOfItems: 3,
selectedIndex: _currentPage,
),
)
],
),
),
);
}
@override
void dispose() {
_pageController.dispose();
_timer.cancel();
super.dispose();
}
}
class TestPage extends StatelessWidget {
final int? id;
final Color color;
final String text;
const TestPage({Key? key, this.id, required this.color, required this.text})
: super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: [
Container(
height: 200,
width: 200,
color: color,
),
const SizedBox(height: 100),
Text(text),
],
);
}
}
class CustomIndicator extends StatelessWidget {
final int noOfItems;
final int selectedIndex;
const CustomIndicator(
{Key? key, required this.noOfItems, required this.selectedIndex})
: super(key: key);
@override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: List.generate(
noOfItems,
(index) => CircleAvatar(
radius: 7,
backgroundColor:
index == selectedIndex ? Colors.green : Colors.grey)),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment