I have a application. Its simply changing background every 1.5 second(default). But I want to control it with a Slider. I changing my state but my timer is inside of initstate. So Its not effecting it. How can i make it ? My Code:
Slider(
value: features.loopTime,
max: 15,
min: 0,
onChanged: (value) {
print(value.toInt());
setState(() {
features.loopTime = value;
});
},
),
InitState:
@override
void initState() {
super.initState();
var loopTime = features.loopTime * 1000;
timer = new Timer.periodic(new Duration(milliseconds: loopTime.toInt()), (Timer timer) {
inspect(loopTime.toInt());
if (!features.isManual) {
setState(() {
features.isBlue = !features.isBlue;
});
}
});
}
CodePudding user response:
You have to cancel timer and reassign. I created function named with _changeTimer() when you slide the slider It will be reassign with new value.
import 'dart:async';
import 'dart:developer';
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
double _loopTime = 1;
bool isBlue = false;
Timer? timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(milliseconds: (1000 * _loopTime).toInt()),
(Timer timer) {
setState(() {
isBlue = !isBlue;
});
});
}
//there
_changeTimer() {
timer!.cancel();
timer = Timer.periodic(Duration(milliseconds: (1000 * _loopTime).toInt()),
(Timer timer) {
setState(() {
isBlue = !isBlue;
});
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Material App',
home: Scaffold(
backgroundColor: isBlue ? Colors.blue : Colors.yellow,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Slider(
activeColor: Colors.black,
value: _loopTime,
max: 15,
min: 0,
onChanged: (value) {
setState(() {
_loopTime = value;
_changeTimer();
});
},
),
Text(_loopTime.toString())
],
),
),
);
}
}