Home > database >  Holding a state within StatefulWidget
Holding a state within StatefulWidget

Time:12-17

I have a settings page where I'm holding a path for a keyfile in SavedPreferences. It is also possible to redefine the path for keyfile in this settings page.

class Settings extends StatefulWidget {
  const Settings({Key? key}) : super(key: key);

  @override
  _SettingsState createState() => _SettingsState();
}

class _SettingsState extends State<Settings> {
    void initState() {
    getSettings();
    super.initState();
  }

  void getSettings() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _keyPath = prefs.getString('keyPath')!;
    _keyFile = _keyPath.split('/').last;
  }
  
  String _keyPath = '';
  String _keyFile = '';

  Future<void> openFile() async {
    SharedPreferences prefs = await SharedPreferences.getInstance();
    _keyPath = (await FlutterFileDialog.pickFile())!;
    setState(() {
      print(_keyPath);
      _keyFile = _keyPath.split('/').last;
      prefs.setString('keyPath', _keyPath);
    });
  }

  @override
  Widget build(BuildContext context) {
    getSettings();
    return Scaffold(
      appBar: AppBar(
        title: const Text('Settings'),
      ),
      body: Column(
        children: [
          Row(
            children: [
              Expanded(
                child: Column(
                  children: [
                    Text('Key File: '),
                    Text(_keyFile),
                  ],
                ),
              ),
              Expanded(
                child: ElevatedButton(onPressed: openFile, child: Text('Open')),
              )
            ],
          )
        ],
      ),
    );
  }
}

This works fine when initializing for first time but when the Widget is already initialized and the navigated back second time I'm having trouble to use the saved key in SharedPreferences when navigating back to this page.

I know I'm getting the value for _keyFile and _keyPath when renavigating in

String _keyPath = '';
String _keyFile = '';

Cant figure out how to call async function when renavigating to widget without initState to use SharedPreferences

I guess this should be done via state and not to query the items from SharedPreferences but I'm little clueless how to do this exactly.

CodePudding user response:

I would suggest you to use a FutureBuilder instead of getting SharedPreferences in InitState:

FutureBuilder(
    future: SharedPreferences.getInstance(),
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      if (snapshot.hasData) {
        // set keys and show your Column widget
      } else if (snapshot.hasError) {
        // Show error widget
      } else {
        // Show loading Widget
      }
    },
  ),
);

Like this you will get the saved value in your SharedPreferences everytime you navigate to this widget. For more information, you can check the doc link.

CodePudding user response:

For example you can use GlobalKey to store the scaffold state in use to show snackbar and etc...

  • Related