Вы можете скопировать и вставить полный код ниже
Чтобы убедиться, что значение правильно сохранено, вы можете использовать PreferenceDialogLink
onPop
для вызова setState
на странице настроек
фрагмент кода
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(() {}),
),
рабочая демонстрация
полный код
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')}'),
],
),
);
}
}