kimSoo
kimSoo

Reputation: 313

Flutter can't show the data in text

I pulled my data and set it with sharedPreferences. And in Future and I can get the country code when I print it. But I cant show it in my Text. Any İdeas? Here's sample code;

  Future<String> getCountryCode() async{
  final countryCodeValue = await SharedPreferences.getInstance();
   countryCode =countryCodeValue.getString('code');
    print('here $countryCode');
    return countryCode;
}

And my text,

Text( countryName != null ? countryName['name'] + ' $countryCode': '',   ),

P.S; I tried calling my method in initState but it didn't work

Upvotes: 0

Views: 119

Answers (4)

timilehinjegede
timilehinjegede

Reputation: 14053

You need to call setState in your getCountryCode method when the Future is done. This will trigger your build function to rebuild and thereby showing the countryCode in the Text widget.

I added a demo using your code as an example:

  Future<String> getCountryCode() async{
  final countryCodeValue = await SharedPreferences.getInstance();
   // call setState 
   setState((){
   countryCode =countryCodeValue.getString('code');
   });
    print('here $countryCode');
    return countryCode;
}

Upvotes: 1

Madhavam Shahi
Madhavam Shahi

Reputation: 1192

Try this,

var countryCode;
getCountryCode() async{
  final countryCodeValue = await SharedPreferences.getInstance();

setState((){
countryCode =countryCodeValue.getString('code');
});
   
    print('here $countryCode');
    

}

Now, in your Text() widget, do this

Text( countryName != null ? countryName['name'] + ' $countryCode': '',   ),

Call getCountryCode() in initState()

Upvotes: 0

maxpill
maxpill

Reputation: 1331

Text(countryName != null ? "$countryName['name'] $countryCode" : "",)

Upvotes: 0

ByteMe
ByteMe

Reputation: 1670

Try this

String countryCode = await getCountryCode();
Text( (countryName != null)? "" + countryName['name'] + ' $countryCode': ''),

Upvotes: 0

Related Questions