I am having a hard time retrieving the user preference in multiple RadioPreference
in a flutter project using the Preferences library https://pub.dev/packages/prefe
You can copy paste run full code below
To make sure value is correctly saved , you can use PreferenceDialogLink
's onPop
to call setState
in Setting page
code snippet
PreferenceDialogLink(
'Android\'s "ListPreference"',
dialog: PreferenceDialog(
[
RadioPreference(
'Select me!', 'select_1', 'android_listpref_selected'),
RadioPreference(
'Hello World!', 'select_2', 'android_listpref_selected'),
RadioPreference('Test', 'select_3', 'android_listpref_selected'),
],
title: 'Select an option',
cancelText: 'Cancel',
submitText: 'Save',
onlySaveOnSubmit: true,
),
onPop: () => setState(() {}),
),
working demo
full code
import 'package:flutter/material.dart';
import 'package:preferences/preferences.dart';
import 'package:validators/validators.dart';
main() async {
WidgetsFlutterBinding.ensureInitialized();
await PrefService.init(prefix: 'pref_');
PrefService.setDefaultValues({
'user_description': 'This is my description!',
});
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Preferences Demo',
home: MyHomePage(title: 'Preferences Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: PreferencePage([
PreferenceTitle('General'),
PreferenceText(
PrefService.getString('android_listpref_selected') ?? '',
style: TextStyle(color: Colors.grey),
),
PreferenceDialogLink(
'Android\'s "ListPreference"',
dialog: PreferenceDialog(
[
RadioPreference(
'Select me!', 'select_1', 'android_listpref_selected'),
RadioPreference(
'Hello World!', 'select_2', 'android_listpref_selected'),
RadioPreference('Test', 'select_3', 'android_listpref_selected'),
],
title: 'Select an option',
cancelText: 'Cancel',
submitText: 'Save',
onlySaveOnSubmit: true,
),
onPop: () => setState(() {}),
),
]),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.push(
context,
MaterialPageRoute(builder: (context) => SecondRoute()),
);
},
child: Icon(Icons.navigation),
backgroundColor: Colors.green,
),
);
}
}
class SecondRoute extends StatelessWidget {
@override
Widget build(BuildContext context) {
print('${PrefService.getString('android_listpref_selected')}');
return Scaffold(
appBar: AppBar(
title: Text("Second Route"),
),
body: Column(
children: <Widget>[
Text('${PrefService.getString('android_listpref_selected')}'),
],
),
);
}
}