I'm working to do a simple countdown and it works great
but the problem is that when I switch to another page, the countdown counter does not continue from where it left off.
eg I initialize the counter: 10 , 9, 8 ...
the page changes and the counter starts again at 10
here is my code
My package: import 'package:circular_countdown_timer/circular_countdown_timer.dart';
class _CircularTimerState extends State<CircularTimer> {
final CountDownController controller = CountDownController();
@override
void initState() {
super.initState();
}
void miningCounter() {
controller.start();
final user = context.read<FirebaseAuthMethods>().user;
dbRef.child(user.uid).child('miningEndTime').set(endTime);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Circular Timer'),
backgroundColor: primaryMaterialColor,
),
body: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Countdown Start Button
CustomMiningButton(
icon: Icons.start,
onTap: miningCounter,
),
CircularCountDownTimer(
duration: 10,
initialDuration: 0,
controller: controller,
width: MediaQuery.of(context).size.width * 0.2,
height: MediaQuery.of(context).size.height * 0.2,
autoStart: false,
),
],
),
);
}
}
CodePudding user response:
You need to remember what was the last number. You can use the SharedPreferences package:
Create a class:
class SharedPref {
static late final SharedPreferences prefs;
static initialize() async {
prefs = await SharedPreferences.getInstance();
}
SharedPref._();
}
Call the initialize method in your main function:
void main() async {
await SharedPref.initialize();
runApp(...);
}
Then before you open the next page you save the value:
SharedPref.prefs.setInt("remaining", _remaining);
Have a variable that holds this number:
final CountDownController controller = CountDownController();
late int _remaining;
bool _loading = true;
@override
void initState() {
super.initState();
_setRemaining();
}
_setRemaining() async {
_remaining = await SharedPref.prefs.getInt("remaining");
setState(() { _loading = false; });
}
...
body: _loading ? CircularProgressIndicator() : Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Countdown Start Button
CustomMiningButton(
icon: Icons.start,
onTap: miningCounter,
),
CircularCountDownTimer(
duration: 10,
initialDuration: _remaining,
controller: controller,
width: MediaQuery.of(context).size.width * 0.2,
height: MediaQuery.of(context).size.height * 0.2,
autoStart: false,
),
],
),
CodePudding user response:
I think passing key to the page would work
Here is YouTube vedio for your case :-https://www.youtube.com/watch?v=sMD4Qxn9q_E