Flutter: Preferencias compartidas nulas en el inicio
Problema: el valor bool de preferencia compartida esnull
en el inicio a pesar de que le he dado un valor siprefs.getBool('myBool')
devolucionesnull
(aunque mi valor de preferencias compartidas ya debería estar configurado y guardado). Sin embargo, funciona cuando presiono un botón (supongo que porque ha terminado de ejecutar el código asíncrono).
Pregunta: ¿Cómo puedo forzar que las preferencias compartidas se carguen al inicio (entonces mi valor no esnull
) sin tener que presionar el botón imprimir?
Código de ejemplo:
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
void main() => runApp(new MyApp());
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
final padding = const EdgeInsets.all(50.0);
@override
void initState() {
super.initState();
MySharedPreferences.load();
MySharedPreferences.printMyBool();
}
@override
Widget build(BuildContext context) {
return new MaterialApp(
home: new Scaffold(
body: new Padding(
padding: padding,
child: new Column(
children: <Widget>[
new Padding(
padding: padding,
child: new RaisedButton(
child: new Text('Save True'),
onPressed: () => MySharedPreferences.save(myBool: true),
),
),
new Padding(
padding: padding,
child: new RaisedButton(
child: new Text('Save False'),
onPressed: () => MySharedPreferences.save(myBool: false),
),
),
new Padding(
padding: padding,
child: new RaisedButton(
child: new Text('Print myBool'),
onPressed: () => MySharedPreferences.printMyBool(),
),
),
],
),
),
),
);
}
}
class MySharedPreferences {
static bool _myBool;
static void load() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_myBool = prefs.getBool('myBool') ?? false;
}
static void save({myBool: bool}) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
_myBool = myBool;
await prefs.setBool('myBool', _myBool);
}
static void printMyBool() {
print('myBool: ${_myBool.toString()}');
}
}
Resultados: al inicio,myBool: null
está impreso. Una vez que se presiona el botón,myBool: false/true
Luego se imprime.