I move a slider and I have a value. Is it possible, by modifying this value through another widget, to modify the slider so that there is always a correspondence between the value and the slider itself?
I mean: if I increase the value by 100, for example, i need the dot slider change too.
Thx
CodePudding user response:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key:
key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
double sliderValue = 50;
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan,
appBar: AppBar(
title: Text(widget.title),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
'${sliderValue.toStringAsFixed(1)}',
style: TextStyle(color: Colors.white),
),
Slider(
value: sliderValue,
min: 0,
max: 100,
divisions: 100,
onChanged: (val) {
setState(() {
sliderValue = val;
});
},
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: [
ElevatedButton.icon(
onPressed: () {
setState(() {
if (sliderValue - 1 > -1) sliderValue -= 1;
});
},
icon: Icon(Icons.arrow_left),
label: Text('Decrease'),
),
ElevatedButton.icon(
onPressed: () {
setState(() {
if (sliderValue < 100.0) sliderValue = 1;
});
},
icon: Icon(Icons.arrow_right),
label: Text('Increase'),
)
],
)
],
),
);
}
}