Skip to content

Instantly share code, notes, and snippets.

@codesxt
Created October 16, 2023 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save codesxt/95f7b2550e404ac46b440ae55a67b301 to your computer and use it in GitHub Desktop.
Save codesxt/95f7b2550e404ac46b440ae55a67b301 to your computer and use it in GitHub Desktop.
Settings storage example with shared_preferences
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,
),
),
),
],
),
);
}
}
@codesxt
Copy link
Author

codesxt commented Oct 16, 2023

Screenshot_1697487216

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment