简体   繁体   中英

Flutter Dart Singleton Data 'Lost'

I want to use the following class to store account data to make it accessible to every part of the app.

class AccountData {
  static AccountData _instance = new AccountData._internal();

  static GoogleSignInAccount _googleData;

  factory AccountData() {
    return _instance;
  }

  AccountData._internal();

  static void setData(GoogleSignInAccount googleData)
  {
    _googleData = googleData;
  }

  GoogleSignInAccount get getData{
    return _googleData;
  }

  String getUserID(){
    return "5";
  }

  List<Workout> getWorkouts(){
    return null;
  }

  Workout getWorkoutByDate(String workoutID, String date)
  {
    return null;
  }
}

I setup the google account after the user logged in, using the following code.

 _googleSignIn.onCurrentUserChanged.listen((GoogleSignInAccount account) {
      AccountData.setData(account);

      print("Logged in, id: " + account.id);
      runApp(new HomeState());
    });

At this point I can access all fields of account and everything is working fine. The only way to get past the login screen is through this part of the code. Therefore the account data always gets assigned.

@override
  void initState() {
    super.initState();

    AccountData d = new AccountData();
    print(d.getData);
}

If I try to access the account data in the HomeState, the GoogleSignInAccount that gets returned is null which it shouldn't be. I hope that someone knows why this happens and knows how to solve the problem.

You are storing the data in a static variable of the class from a static method AccountData.setData(account);

You should also statically access the data to recover them:

AccountData.getData();

Previously, you need to define the method as static in the class body:

static GoogleSignInAccount get getData{
    return _googleData;
}

Then, since everything is static for the _googleData you don't need to create an instance of AccountData.

Otherwise, you could change all of them to be instance variable and methods, and you should create the instance upfront.

had the same issue with one of my pages. you should have a way of checking if the async _googleSignIn account data is received as @chemamolins said. as far as i know the initState function does not wait till the data is recieved, and it continues to render your page with a null value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM