Global variable seems to be empty

Hi everybody,

this behaviour is really strange.
I have a welcome.dart which is my app’s start screen. In this file I have a if-condition directly under the Widget build() statement:
Widget build(context) {
if(username == ‘’) {
return Container(
color: Colors.white,
child: SafeArea( …

The variable username comes from globals.dart which contains all global variables:
library my_prj.globals;
List favList = [];
String homeLocation = ‘’;
String uid = ‘’;
String username = ‘’;
String selectedLoc;
String token;

I save/read the entries (e.g. username) with a shared_preferences method and execute the method in the welcome’s initState method:
void saveName() async {
var prefs = await SharedPreferences.getInstance();
var key = ‘name’;
await prefs.setString(key, username);
print(’$username saved as username’);

Future readName() async {
var prefs = await SharedPreferences.getInstance();
var key = ‘name’;
username = prefs.getString(key);
print(’$username read as username’);
return username;

But the problem is when the app is loading and the read method will be executed the username shows nothing so every time the if-statement will be executed and not the else. I don’t not why. The methods work fine in other parts of the code. Is there something special because of the if-statement inside of Widget build() ? Or have anyone an other option to solve my problem?

Thanks in advance.

Could you please write the full code with ``` content ``` syntax? Put your code between them.

We use dart so you should do it like this

``` dart
Your Code

1 Like

Problem is solved.
The solution was catching the results with another future.
So in the past the future was executed but the result was not yet there.