inital value of _value is 200, but when i change the value with the slider, it does not pass it to the controller (i mean because of init it takes as default 200 and never changes)
int _value = 200;
@override
void initState() {
super.initState();
_yellowController = AnimationController(
duration: Duration(milliseconds: _value), vsync: this)
..addListener(() {
setState(() {});
});
}
Slider(
min: 200,
max: 2000,
activeColor: Colors.black54,
inactiveColor: Colors.black12,
thumbColor: Colors.black,
value: _value.toDouble(),
onChanged: (value) {
_value = value.round();
setState(() {});
},
),
CodePudding user response:
You need to delete setState(() {});
into addListener
code. Because it's doing automatically. If you do setState
in addListener
code it's rebuild again and returns to starting position
CodePudding user response:
You can see this StackOverflow answer that you can just change the _yellowController.duration
and animate foward
/reverse
/repeat
again. Try this code on https://dartpad.dev/ :
import 'package:flutter/material.dart';
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 MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
const MyWidget({super.key});
@override
createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget>
with SingleTickerProviderStateMixin {
int _value = 200;
late AnimationController _yellowController;
late Animation<double> animation;
@override
void initState() {
super.initState();
_yellowController = AnimationController(
duration: Duration(milliseconds: _value),
vsync: this,
);
_yellowController.repeat(reverse: true);
animation = Tween<double>(begin: 0, end: 1).animate(_yellowController);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('AppBar Title'),
),
body: Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
AnimatedBuilder(
animation: animation,
builder: (context, child) {
return Transform.scale(
scale: animation.value,
child: child!,
);
},
child: const SizedBox.square(
dimension: 50,
child: ColoredBox(
color: Colors.white,
),
),
),
Slider(
min: 200,
max: 2000,
activeColor: Colors.black54,
inactiveColor: Colors.black12,
thumbColor: Colors.black,
value: _value.toDouble(),
onChanged: (value) {
_yellowController.duration = Duration(milliseconds: value.round());
_yellowController.repeat(reverse: true);
_value = value.round();
setState(() {});
},
),
],
),
),
);
}
}