Hello in my app I will control my fontSize
with a Slider
and control the slider with a checkbox
so if the user wants to change the size they will enable the checkbox so
i want that if user will change the slider to change the font that will save in local storage of that device how can i do it?
code:
bool toggle = false;
int _value = 38;
Expanded(
flex: 2,
child:
Switcher(
size:SwitcherSize.small,
curveType: Curves.fastLinearToSlowEaseIn,
colorOn: Colors.green,
colorOff: Colors.redAccent,
iconOn: Icons.done,
iconOff: Icons.dangerous,
onChanged: (value) {
toggle = value;
},
),
),
Expanded(
flex: 12,
child: Slider(
thumbColor: Colors.red.shade900,
value: _value.toDouble(),
activeColor: Colors.black,
inactiveColor: Colors.grey.shade400,
onChanged: (double s) {
setState(() {
if (toggle == false) {
return null;
}
if (toggle == true) {
_value = s.toInt();
}
});
},
min: 20.0,
max: 60.0,
),
// switchcase(),
),
//call here
fontSize: _value.toDouble(),
this code will properly plz tell me how i will save this in shared pref
You can try this:
import 'package:shared_preferences/shared_preferences.dart';
class MySliderWidget extends StatefulWidget {
const MySliderWidget({super.key});
@override
State<MySliderWidget> createState() => _MySliderWidgetState();
}
class _MySliderWidgetState extends State<MySliderWidget> {
bool toggle = false;
double _value = 38;
late SharedPreferences _pref;
String prefKey = "value";
// function to save to pref
void saveOnPref(double value) async {
_pref = await SharedPreferences.getInstance();
_pref.setDouble(prefKey, value);
}
// this function load and update value
void loadFromPref() async {
_pref = await SharedPreferences.getInstance();
setState(() {
_value = _pref.getDouble(prefKey) ?? 38.0;
});
}
@override
void initState() {
loadFromPref();
super.initState();
}
@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
"test",
style: TextStyle(fontSize: _value),
),
Switch(
onChanged: (value) {
setState(() {
toggle = !toggle;
});
},
value: toggle,
),
Slider(
thumbColor: Colors.red.shade900,
value: _value,
activeColor: Colors.black,
inactiveColor: Colors.grey.shade400,
min: 20.0,
max: 60.0,
onChanged: toggle
? (value) {
setState(() {
_value = value;
});
saveOnPref(value);
}
: null,
)
],
);
}
}
result: