How To Retrieve RadioPreference, CheckPreference values in Preferences in Flutter

让人想犯罪 __ 提交于 2021-02-17 05:52:05

问题


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/preferences#. I know how to use SharedPreferences in Flutter but after following the example in the preference page, I can't seems to retrieve the actual user selection.

For example

 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,
      ),
    ),

    PreferenceDialogLink(
      'Android\'s "MultiSelectListPreference"',
      dialog: PreferenceDialog(
        [
          CheckboxPreference('A enabled', 'android_multilistpref_a'),
          CheckboxPreference('B enabled', 'android_multilistpref_b'),
          CheckboxPreference('C enabled', 'android_multilistpref_c'),
        ],
        title: 'Select multiple options',
        cancelText: 'Cancel',
        submitText: 'Save',
        onlySaveOnSubmit: true,
      ),
    ),

After leaving the Setting page, I tried using PrefService.getString('android_listpref_selected'); and other variations I keep getting null. Any help is appreciated.


回答1:


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')}'),
        ],
      ),
    );
  }
}


来源:https://stackoverflow.com/questions/60801696/how-to-retrieve-radiopreference-checkpreference-values-in-preferences-in-flutte

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!