Last active
November 7, 2022 11:17
-
-
Save manthri-mohan-sai/f6810e5d065d2c103d18579c655ddee8 to your computer and use it in GitHub Desktop.
Pausing timer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'dart:async'; | |
const Color darkBlue = Color.fromARGB(255, 18, 32, 47); | |
void main() { | |
runApp(MyApp()); | |
} | |
class MyApp extends StatelessWidget { | |
@override | |
Widget build(BuildContext context) { | |
return MaterialApp( | |
theme: ThemeData.dark().copyWith( | |
scaffoldBackgroundColor: darkBlue, | |
), | |
debugShowCheckedModeBanner: false, | |
home: const Scaffold( | |
body: Center( | |
child: MyWidget(), | |
), | |
), | |
); | |
} | |
} | |
class SecondWidget extends StatefulWidget { | |
const SecondWidget({Key? key}) : super(key: key); | |
@override | |
State<SecondWidget> createState() => _MySecondWidgetState(); | |
} | |
class _MySecondWidgetState extends State<SecondWidget> { | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
body: Column( | |
children: [ | |
Text('Second page'), | |
ElevatedButton( | |
child: Text('Go Back'), | |
onPressed: () async { | |
Navigator.of(context).pop(); | |
}), | |
], | |
), | |
); | |
} | |
} | |
class MyWidget extends StatefulWidget { | |
const MyWidget({Key? key}) : super(key: key); | |
@override | |
State<MyWidget> createState() => _MyWidgetState(); | |
} | |
class _MyWidgetState extends State<MyWidget> { | |
Timer? timer; | |
@override | |
void initState() { | |
super.initState(); | |
initTimer(); | |
} | |
void initTimer() { | |
timer = Timer.periodic(Duration(seconds: 1), (Timer t) { | |
print("Running"); | |
}); | |
} | |
@override | |
void dispose() { | |
print( | |
'test \n if you are seeing this, maybe you used Navigator.pushReplacement()'); | |
timer?.cancel(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Column( | |
children: [ | |
Text('First page'), | |
ElevatedButton( | |
child: Text('Second page'), | |
onPressed: () async { | |
timer?.cancel(); | |
await Navigator.of(context).push( | |
MaterialPageRoute(builder: (context) => SecondWidget())); | |
initTimer(); | |
}), | |
], | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment