Add 30 seconds more to the timer - flutter

Hello I am doing a flutter app , and I want to use a button to add 30s more to the time when it's pressed. The timer starts with 60 seconds , but I want the user to be able to add 30 seconds more if he needs . I only find at the controller(of time) the options like: reverse() , reset() , resync() but nothing to add the time. This is what I used in the beginning of the code ( I will post only some paths because the code is very big)
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
AnimationController controller;
String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: Duration(seconds: 60),
);
}
and this is how I write my code for the button with +30s but it only reset the time to 00:30seconds.
child: RaisedButton(
onPressed: () {
if (controller.isAnimating)
controller.duration = Duration(seconds: 30);
},
color: Colors.white,
shape: RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30),
),
textColor: Colors.black,
child: Text("Give player +30s ")),
),

Here is a Solution using an AnimationController combined with a Timer. I used an initial time of 10 seconds and a time increase of 5 seconds for a faster demo.
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Timer Demo',
home: HomePage(),
),
);
}
class HomePage extends StatefulWidget {
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool done = false;
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: done
? Text('TIME OUT')
: CountDownTimer(
onCompleted: () => setState(() => done = true),
),
),
);
}
}
class CountDownTimer extends StatefulWidget {
final VoidCallback onCompleted;
const CountDownTimer({
Key key,
this.onCompleted,
}) : super(key: key);
#override
_CountDownTimerState createState() => _CountDownTimerState();
}
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
AnimationController _controller;
Timer _timer;
int _elapsed;
#override
void initState() {
super.initState();
// AnimationController
_controller = AnimationController(vsync: this, duration: kInitialTime);
_controller.addListener(() => setState(() {}));
_controller.addStatusListener(
(AnimationStatus status) {
if (status == AnimationStatus.completed) {
_timer.cancel();
widget.onCompleted();
}
},
);
// Elapsed Counter
_elapsed = 0;
_timer = Timer.periodic(
Duration(seconds: 1),
(_) => setState(() => _elapsed++),
);
// Launch the Controller
_controller.forward();
}
void increaseTime([int extraTime = kExtraTime]) {
_controller.duration =
Duration(seconds: _controller.duration.inSeconds + extraTime);
_controller.reset();
_controller.forward(from: _elapsed / _controller.duration.inSeconds);
}
#override
void dispose() {
_controller.dispose();
_timer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(
value: _controller.value,
backgroundColor: Colors.black12,
),
const SizedBox(height: 12.0),
Text('$_elapsed / ${_controller.duration.inSeconds}'),
const SizedBox(height: 24.0),
ElevatedButton(
onPressed: () => increaseTime(),
child: Text('MORE TIME'),
),
],
);
}
}
// CONFIGURATION
const Duration kInitialTime = Duration(seconds: 10);
const int kExtraTime = 5;

You are setting the duration to 30 seconds, what you need to do instead is add to the remaining duration. You can probably use the + operator of the Duration class: https://api.dart.dev/stable/2.10.5/dart-core/Duration/operator_plus.html
Something like this:
onPressed: () {
if (controller.isAnimating) {
controller.duration += Duration(seconds: 30);
}
},
Not sure if the controller actually supports this.

Related

Lottie Animation works only once on tap

I am using Lottie Animation and want it to animate everytime I click on it , To this I am using GestureDetector However it only works the first time then for some reason it wont work again
Here is the code
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
void main() async {
runApp(const App());
}
class App extends StatefulWidget {
const App({super.key});
#override
State<App> createState() {
return _AppState();
}
}
class _AppState extends State<App> with SingleTickerProviderStateMixin {
late final AnimationController my_location_controller;
#override
void initState() {
// TODO: implement initState
super.initState();
my_location_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 5));
}
#override
Widget build(BuildContext context) {
return MaterialApp(
color: Colors.lightBlue,
home: Scaffold(
backgroundColor: Colors.lightBlue,
body: Center(
child: SizedBox(
width: 300,
height: 300,
child: GestureDetector(
onTap: () {
my_location_controller.forward();
},
child: Lottie.asset(
'assets/my_location.json',
controller: my_location_controller,
animate: true,
repeat: true,
),
),
),
),
),
);
}
}
#Ante Bule thnx, will accept your answer and this seems to work too ..
child: GestureDetector(
onTap: () {
my_location_controller.reset();
my_location_controller.forward();
},
child: Lottie.asset(
'assets/my_location.json',
controller: my_location_controller,
),
Add a listener to reset your animation when it gets completed, like this:
#override
void initState() {
super.initState();
my_location_controller =
AnimationController(vsync: this, duration: const Duration(seconds: 5));
my_location_controller.addStatusListener((status) {
if (status == AnimationStatus.completed) {
my_location_controller.reset();
}
});
}

how to display an image in flutter after every 5 seconds?

i am new at flutter and building a project in which a distractor appears after every 5 sec on the the screen. i am using timer periodic but it the picture does not appears after 5 seconds rather it get displayed randomly after a few times. it starts to flash the image on the screen rather then keeping it displayed. also pictures doesnt appear after set time rather it changes its time itself. please help me. i am sad.
...
import 'dart:async';
import 'dart:math';
import 'package:flutter/material.dart';
class adhd1 extends StatefulWidget {
const adhd1({Key? key}) : super(key: key);
#override
State<adhd1> createState() => _adhd1State();
}
class _adhd1State extends State<adhd1> {
int a = 4;
bool distractor1 = false;
bool? distractor2 = false;
bool? distractor3 = false;
bool? distractor4 = false;
late Duration tt;
late Duration ff;
#override
Widget build(BuildContext context) {
showD1() {
Timer.periodic(
tt = Duration(seconds: 4),
(Timer t) => setState(() {
distractor1 = true;
t.cancel();
}));
Timer.periodic(
ff = Duration(seconds: 5),
(Timer d) => setState(() {
distractor1 = false;
d.cancel();
}));
if (distractor1) {
return SizedBox(
height: 200,
child: Image.asset(
"assets/images/character_robot_attack0.png",
fit: BoxFit.contain,
));
} else {
return const SizedBox(
height: 200,
);
}
}
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
children: [showD1()],
)));
}
}
...
To show for 2 second and hide 5sec, I am using AnimationController
class AnimeTestW extends StatefulWidget {
AnimeTestW({Key? key}) : super(key: key);
#override
State<AnimeTestW> createState() => _AnimeTestWState();
}
class _AnimeTestWState extends State<AnimeTestW>
with SingleTickerProviderStateMixin {
late AnimationController controller;
#override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: const Duration(seconds: 2),
reverseDuration: const Duration(seconds: 5),
)
..addListener(() {
print(controller.status);
if (controller.status == AnimationStatus.completed) {
controller.reverse();
}
if (controller.status == AnimationStatus.dismissed) {
controller.forward();
}
setState(() {});
})
..forward();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(onPressed: () {
controller.reverse();
}),
body: Column(
children: [
Text("A"),
if (controller.status == AnimationStatus.forward)
Container(
width: 100,
height: 100,
color: Colors.red,
)
],
),
);
}
}
Use initState with a state bool
class _adhd1State extends State<adhd1> {
Timer? timer;
bool showImage = false;
#override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 5), (timer) {
setState(() {
showImage = !showImage;
});
});
}
#override
void dispose() {
timer?.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
body: Center(
child: Column(
children: [
if (showImage)
Image.asset(
"assets/images/character_robot_attack0.png",
fit: BoxFit.contain,
)
],
),
),
);
}
}

How Animate Like Button in Flutter

I would like to ask you how to animate the size of an icon when you click on an image like on Instagram, Tiktok...
This is what I tried (and many other things) but without success.
GestureDetector(
onDoubleTap: (){
setState(() {
_showLikeAnimation = true;
_sizeFavoriteAnimation = 60.0; //old value is 20.0
});
},
child: Stack(
alignment: AlignmentDirectional.center,
children: [
_imagePost(),
AnimatedSize(curve: Curves.easeIn, duration: const Duration(seconds: 2), child: Icon(Icons.favorite, size: _sizeFavoriteAnimation))
],
)),
Would you have an idea?
One way you can achieve this is by using ScaleTransition and a CurvedAnimation. Below is a simple example.
When the user taps the icon, I change the look of the icon so it shows the latest state (active/not active) and I make it a little smaller. When this transition ends I make the icon big again. This is similar to how a button behaves in the real world when you press it. I hope this is what you had in mind.
class LikeButton extends StatefulWidget {
const LikeButton({Key? key}) : super(key: key);
#override
State<LikeButton> createState() => _LikeButtonState();
}
class _LikeButtonState extends State<LikeButton>
with SingleTickerProviderStateMixin {
late final AnimationController _controller = AnimationController(
duration: const Duration(milliseconds: 200), vsync: this, value: 1.0);
bool _isFavorite = false;
#override
void dispose() {
super.dispose();
_controller.dispose();
}
#override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_isFavorite = !_isFavorite;
});
_controller
.reverse()
.then((value) => _controller.forward());
},
child: ScaleTransition(
scale: Tween(begin: 0.7, end: 1.0).animate(
CurvedAnimation(parent: _controller, curve: Curves.easeOut)),
child: _isFavorite
? const Icon(
Icons.favorite,
size: 30,
color: Colors.red,
)
: const Icon(
Icons.favorite_border,
size: 30,
),
),
);
}
}
You can use https://pub.dev/packages/lottie to animate,
try this;
import 'package:flutter/material.dart';
import 'package:lottie/lottie.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return const MaterialApp(title: 'Material App', home: LottieLearn());
}
}
class LottieLearn extends StatefulWidget {
const LottieLearn({Key? key}) : super(key: key);
#override
State<LottieLearn> createState() => _LottieLearnState();
}
class _LottieLearnState extends State<LottieLearn> with TickerProviderStateMixin {
#override
Widget build(BuildContext context) {
final AnimationController darkmodeController =
AnimationController(vsync: this, duration: const Duration(seconds: 2));
final AnimationController favoriteController =
AnimationController(vsync: this, duration: const Duration(seconds: 1));
bool isLight = false;
bool isFavorite = false;
const String favoriteButton = "https://assets10.lottiefiles.com/packages/lf20_slDcnv.json";
const String darkMode = "https://assets10.lottiefiles.com/packages/lf20_tbyegho2.json";
return Scaffold(
appBar: AppBar(
actions: [
InkWell(
onTap: () async {
await darkmodeController.animateTo(isLight ? 0.5 : 1);
// controller.animateTo(0.5);
isLight = !isLight;
},
child: Lottie.network(darkMode, repeat: false, controller: darkmodeController)),
InkWell(
onTap: () async {
await favoriteController.animateTo(isFavorite ? 1 : 0);
isFavorite = !isFavorite;
},
child: Lottie.network(favoriteButton, repeat: false, controller: favoriteController)),
],
),
);
}
}
this must give you an idea, just "flutter pub add lottie" then copy paste code

Flutter Reworked question: Issue sharing states between widget with button and widget with countdown timer

I am trying since some days to connect an animated stateful child widget with a countdown timer to the parent stateful widget with the user interaction. I found this answer from Andrey on a similar question (using Tween which I do not) that already helped a lot, but I still don't get it to work. My assumption is, the child's initState could be the reason. The timer's code comes from here.
I have removed quite some code including some referenced functions/classes. This should provide a clearer picture on the logic:
In MainPageState I declare and init the _controller of the animation
In MainPageState I call the stateless widget CreateKeypad hosting among others the "go" key
When go is clicked, this event is returned to MainPageState and _controller.reverse(from: 1.0); executed
In MainPageState I call the stateful widget CountDownTimer to render the timer
In _CountDownTimerState I am not sure if my initState is correct
In _CountDownTimerState I build the animation with CustomTimerPainter from the timer code source
The animation shall render a white donut and a red, diminishing arc on top. However, I only see the white donut, not the red timer's arc. Any hint is highly appreciated.
class MainPage extends StatefulWidget {
MainPage({Key key, this.title}) : super(key: key);
final String title;
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
AnimationController _controller;
var answer="0", correctAnswer = true, result = 0;
#override
void initState() {
super.initState();
_controller = AnimationController(vsync: this, duration: Duration(seconds: 7));
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
navigationBar: CupertinoNavigationBar(
),
child: SafeArea(
child: Container(
child: Column(
children: <Widget>[
CreateKeypad( // creates a keypad with a go button. when go is clicked, countdown shall start
prevInput: int.parse((answer != null ? answer : "0")),
updtedInput: (int val) {
setState(() => answer = val.toString());
},
goSelected: () {
setState(() {
if (answer == result.toString()) {
correctAnswer = true;
}
final problem = createProblem();
result = problem.result;
});
_controller.reverse(from: 1.0); // start the countdown animation
Future.delayed(const Duration(milliseconds: 300,),
() => setState(() => correctAnswer = true));
},
),
CountDownTimer(_controller), // show countdown timer
]
),
),
)
);
}
}
// CREATE KEYPAD - all keys but "1! and "go" removed
class CreateKeypad extends StatelessWidget {
final int prevInput;
final VoidCallback goSelected;
final Function(int) updtedInput;
CreateKeypad({#required this.prevInput, #required this.updtedInput, this.goSelected});
#override
Widget build(BuildContext context) {
return Row(
children: <Widget> [
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(2.0),
child: SizedBox(
width: 80.0, height: 80.0,
child: CupertinoButton(
child: Text("1", style: TextStyle(color: CupertinoColors.black)),
onPressed: () {
updtedInput(1);
},
),
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: SizedBox(
width: 80.0, height: 80.0,
child: CupertinoButton(
child: Text("Go!", style: TextStyle(color: CupertinoColors.black)),
onPressed: () => goSelected(),
),
),
),
],
),
]
);
}
}
// CREATE COUNTDOWN https://medium.com/flutterdevs/creating-a-countdown-timer-using-animation-in-flutter-2d56d4f3f5f1
class CountDownTimer extends StatefulWidget {
CountDownTimer(this._controller);
final AnimationController _controller;
#override
_CountDownTimerState createState() => _CountDownTimerState();
}
class _CountDownTimerState extends State<CountDownTimer> with TickerProviderStateMixin {
#override
void initState() {
super.initState(); // here I have some difference to Andrey's answer because I do not use Tween
}
String get timerString {
Duration duration = widget._controller.duration * widget._controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60)
.toString()
.padLeft(2, '0')}';
}
#override
Widget build(BuildContext context) {
return Container(
child: AnimatedBuilder(
animation: widget._controller,
builder:
(BuildContext context, Widget child) {
return CustomPaint(
painter: CustomTimerPainter( // this draws a white donut and a red diminishing arc on top
animation: widget._controller,
backgroundColor: Colors.white,
color: Colors.red,
));
},
),
);
}
}
You can copy paste run full code below
Step 1: You can put controller inside CountDownTimerState
Step 2: Use GlobalKey
CountDownTimer(key: _key)
Step 3: Call function start() inside _CountDownTimerState with _key.currentState
goSelected: () {
setState(() {
...
_controller.reverse(from: 10.0); // start the countdown animation
final _CountDownTimerState _state = _key.currentState;
_state.start();
...
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
AnimationController _controller;
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 7));
super
.initState(); // here I have some difference to Andrey's answer because I do not use Tween
}
...
void start() {
setState(() {
_controller.reverse(from: 1.0);
});
}
working demo
full code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'dart:math' as math;
class MainPage extends StatefulWidget {
MainPage({Key key, this.title}) : super(key: key);
final String title;
#override
_MainPageState createState() => _MainPageState();
}
class _MainPageState extends State<MainPage> with TickerProviderStateMixin {
AnimationController _controller;
var answer = "0", correctAnswer = true, result = 0;
GlobalKey _key = GlobalKey();
#override
void initState() {
super.initState();
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 7));
}
#override
void dispose() {
_controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return CupertinoPageScaffold(
//navigationBar: CupertinoNavigationBar(),
child: SafeArea(
child: Container(
color: Colors.blue,
child: Column(children: <Widget>[
CreateKeypad(
// creates a keypad with a go button. when go is clicked, countdown shall start
prevInput: int.parse((answer != null ? answer : "0")),
updtedInput: (int val) {
setState(() => answer = val.toString());
},
goSelected: () {
setState(() {
if (answer == result.toString()) {
correctAnswer = true;
}
/*final problem = createProblem();
result = problem.result;*/
});
print("go");
_controller.reverse(from: 10.0); // start the countdown animation
final _CountDownTimerState _state = _key.currentState;
_state.start();
/* Future.delayed(
const Duration(
milliseconds: 300,
),
() => setState(() => correctAnswer = true));*/
},
),
Container(
height: 400,
width: 400,
child: CountDownTimer(key: _key)), // show countdown timer
]),
),
));
}
}
// CREATE KEYPAD - all keys but "1! and "go" removed
class CreateKeypad extends StatelessWidget {
final int prevInput;
final VoidCallback goSelected;
final Function(int) updtedInput;
CreateKeypad(
{#required this.prevInput, #required this.updtedInput, this.goSelected});
#override
Widget build(BuildContext context) {
return Row(children: <Widget>[
Column(
children: <Widget>[
Padding(
padding: const EdgeInsets.all(2.0),
child: SizedBox(
width: 80.0,
height: 80.0,
child: CupertinoButton(
child:
Text("1", style: TextStyle(color: CupertinoColors.black)),
onPressed: () {
updtedInput(1);
},
),
),
),
Padding(
padding: const EdgeInsets.all(2.0),
child: SizedBox(
width: 80.0,
height: 80.0,
child: CupertinoButton(
child:
Text("Go!", style: TextStyle(color: CupertinoColors.black)),
onPressed: () => goSelected(),
),
),
),
],
),
]);
}
}
// CREATE COUNTDOWN https://medium.com/flutterdevs/creating-a-countdown-timer-using-animation-in-flutter-2d56d4f3f5f1
class CountDownTimer extends StatefulWidget {
CountDownTimer({Key key}) : super(key: key);
//final AnimationController _controller;
#override
_CountDownTimerState createState() => _CountDownTimerState();
}
class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
AnimationController _controller;
#override
void initState() {
_controller =
AnimationController(vsync: this, duration: Duration(seconds: 7));
super
.initState(); // here I have some difference to Andrey's answer because I do not use Tween
}
String get timerString {
Duration duration = _controller.duration * _controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}
void start() {
setState(() {
_controller.reverse(from: 1.0);
});
}
#override
Widget build(BuildContext context) {
return Container(
color: Colors.green,
child: AnimatedBuilder(
animation: _controller,
builder: (BuildContext context, Widget child) {
return CustomPaint(
painter: CustomTimerPainter(
// this draws a white donut and a red diminishing arc on top
animation: _controller,
backgroundColor: Colors.green,
color: Colors.red,
));
},
),
);
}
}
class CustomTimerPainter extends CustomPainter {
CustomTimerPainter({
this.animation,
this.backgroundColor,
this.color,
}) : super(repaint: animation);
final Animation<double> animation;
final Color backgroundColor, color;
#override
void paint(Canvas canvas, Size size) {
Paint paint = Paint()
..color = backgroundColor
..strokeWidth = 10.0
..strokeCap = StrokeCap.butt
..style = PaintingStyle.stroke;
canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);
paint.color = color;
double progress = (1.0 - animation.value) * 2 * math.pi;
//print("progress ${progress}");
canvas.drawArc(Offset.zero & size, math.pi * 1.5, -progress, false, paint);
}
#override
bool shouldRepaint(CustomTimerPainter old) {
//print(animation.value);
return true;
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MainPage(),
);
}
}

Stopwatch don't decrease time

I'm trying to make a timer that can be instantiated by any class, but I'm having problems with the TimerWidget class, since its value does not reduce in startTimer(). When called, the class has the same attributes as the TimerWidget class, and as described in the parameter, the timer starts counting with the required value. The errors say that the operator '<' and '-' do not belong to the type Time.
Any suggestions? Tips? I'm new to flutter.
import 'package:flutter/material.dart';
import 'dart:async';
class TimerWidget extends StatefulWidget {
final int hours; // 1 hour:
final int minutes; // 60
final int seconds; // 3.600
final int millisecond; // 3.600.000
final int microsecond; // 3.600.000.000
final int nanosecond; // 3.600.000.000.000
TimerWidget({
this.hours,
this.minutes,
u/required this.seconds,
this.millisecond,
this.microsecond,
this.nanosecond,
});
#override
_TimerWidgetState createState() => _TimerWidgetState();
}
class _TimerWidgetState extends State<TimerWidget> {
Timer _timer;
var start = TimerWidget(seconds: 30);
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (start < 1) {
timer.cancel();
} else {
start = start - 1;
}
},
),
);
}
#override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return new Scaffold(
body: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer();
},
child: Text("start"),
),
Text("$start")
],
),
);
}
}
You can copy paste run full code below
You can use var start = 30; not var start = TimerWidget(seconds: 30);
working demo
full code
import 'package:flutter/material.dart';
import 'dart:async';
class TimerWidget extends StatefulWidget {
final int hours; // 1 hour:
final int minutes; // 60
final int seconds; // 3.600
final int millisecond; // 3.600.000
final int microsecond; // 3.600.000.000
final int nanosecond; // 3.600.000.000.000
TimerWidget({
this.hours,
this.minutes,
#required this.seconds,
this.millisecond,
this.microsecond,
this.nanosecond,
});
#override
_TimerWidgetState createState() => _TimerWidgetState();
}
class _TimerWidgetState extends State<TimerWidget> {
Timer _timer;
var start = 30;
void startTimer() {
const oneSec = const Duration(seconds: 1);
_timer = new Timer.periodic(
oneSec,
(Timer timer) => setState(
() {
if (start < 1) {
timer.cancel();
} else {
start = start - 1;
}
},
),
);
}
#override
void dispose() {
_timer.cancel();
super.dispose();
}
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(title: Text("demo")),
body: Center(
child: Column(
children: <Widget>[
RaisedButton(
onPressed: () {
startTimer();
},
child: Text("start"),
),
Text("$start")
],
),
),
);
}
}
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: TimerWidget(seconds: 30),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}