Using Sharedpreferences to get the default setting in Flutter

Asked

Viewed 118 times

0

Good morning

I’m starting to study Flutter and I was trying to create a Configuration screen, where after configuring the parameters on the screen, you can search at any time, and for this I’m using Sharedpreferences

First I created the Parameter Class as follows

class Parametros{
    LocalSettings settings = LocalSettings();

  String _URL_API;
  String _CodEmpresaPadrao;

  Parametros();

  String get url_api => _URL_API;

  set url_api(String value) {
  
    _URL_API = value;
  }

  String get codempresapadrao => _CodEmpresaPadrao;

  set codempresapadrao(String value){
    _CodEmpresaPadrao = value;
  }
} 

Based on some questions I saw here created the Localsettings

class LocalSettings{
  SharedPreferences preferences;

  Future<void> getInstance() async {
    preferences = await SharedPreferences.getInstance();
  }
}

and then the Search Wire method in the Parameters

void BuscarParametros() async {

    await settings.getInstance();
    if (settings.preferences.containsKey('URL_API'))
      _URL_API = settings.preferences.getString('URL_API');

  } 

But in the configuration screen, when I call the search method to fill the Parameter class, and pass to the text controller, the value null arrives

inserir a descrição da imagem aqui

What I noticed in the debug and that it passes in the search wire, arrives in the line " await Settings.getInstance();" and leaves the method, without passing in time, and after rotating Fillrtxtoparam, it returns in the search wire and rotates everything, even what had not been rotated.

I was wondering if there might be another way to be doing this, or if I might be fixing my code somehow.

  • By default, when naming a function start with lower case letter, for example void buscarParametros(); For classes use the first uppercase letter, for example class PreencherTextParam() (That you’ve done correctly).

  • Thanks for the tip

1 answer

1


Try putting a await before the call to BuscarParametros():

await parametros.BuscarParametros();
setState((){
    _controllerURL.text = paremtros.url_api;
})

You would have been notified since error if you had marked your function with a Future return. For this, modify the signature of your function:

Future<void> BuscarParametros() async {
[...]
}

That way, if you call this function without using await, your IDE will show Warning.

Finally, I believe it is not the heart of the matter, but it is interesting to always be sure to return a default value for when the key is not cached.

  • 1

    It worked, that’s right, thanks for the tips and the attention

Browser other questions tagged

You are not signed in. Login or sign up in order to post.