Created
October 16, 2023 20:26
-
-
Save codesxt/95f7b2550e404ac46b440ae55a67b301 to your computer and use it in GitHub Desktop.
Settings storage example with shared_preferences
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'package:flutter/material.dart'; | |
import 'package:shared_preferences/shared_preferences.dart'; | |
class Home extends StatefulWidget { | |
const Home({super.key}); | |
@override | |
State<Home> createState() => _HomeState(); | |
} | |
class _HomeState extends State<Home> { | |
bool boldText = false; | |
double fontSize = 16; | |
@override | |
void initState() { | |
_initializeVariables(); | |
super.initState(); | |
} | |
_initializeVariables() async { | |
final SharedPreferences prefs = await SharedPreferences.getInstance(); | |
double? fontSizeTemp = prefs.getDouble('fontSize'); | |
if (fontSizeTemp != null) { | |
fontSize = fontSizeTemp; | |
} | |
bool? boldTextTemp = prefs.getBool('boldText'); | |
if (boldTextTemp != null) { | |
boldText = boldTextTemp; | |
} | |
setState(() {}); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: const Text('Ejemplo de Key/Value'), | |
backgroundColor: Theme.of(context).colorScheme.inversePrimary, | |
), | |
body: Column( | |
crossAxisAlignment: CrossAxisAlignment.stretch, | |
mainAxisAlignment: MainAxisAlignment.start, | |
mainAxisSize: MainAxisSize.min, | |
children: [ | |
SwitchListTile( | |
value: boldText, | |
title: const Text('Bold Text'), | |
onChanged: (value) async { | |
boldText = value; | |
setState(() {}); | |
final SharedPreferences prefs = | |
await SharedPreferences.getInstance(); | |
prefs.setBool('boldText', boldText); | |
}, | |
), | |
Row( | |
children: [ | |
Container( | |
padding: const EdgeInsets.only(left: 20), | |
child: Text(fontSize.toStringAsFixed(0)), | |
), | |
Expanded( | |
child: Slider( | |
value: fontSize, | |
min: 10, | |
max: 30, | |
onChanged: (value) { | |
fontSize = value; | |
setState(() {}); | |
}, | |
onChangeEnd: (value) async { | |
final SharedPreferences prefs = | |
await SharedPreferences.getInstance(); | |
prefs.setDouble('fontSize', fontSize); | |
}, | |
), | |
), | |
], | |
), | |
const SizedBox(height: 50), | |
Container( | |
padding: const EdgeInsets.all(20), | |
color: Colors.blue.shade100, | |
child: Text( | |
'Hola Mundo', | |
style: Theme.of(context).textTheme.bodyLarge?.copyWith( | |
fontWeight: boldText ? FontWeight.bold : FontWeight.normal, | |
fontSize: fontSize, | |
), | |
), | |
), | |
], | |
), | |
); | |
} | |
} |
Author
codesxt
commented
Oct 16, 2023
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment