Flutter - How to pass user data to all views

前端 未结 5 637
醉酒成梦
醉酒成梦 2021-01-30 03:10

I\'m new to the flutter world and mobile app development and struggling with how I should pass user data throughout my app.

I\'ve tried several things, but none seem gre

5条回答
  •  北荒
    北荒 (楼主)
    2021-01-30 04:04

    I prefer to use Services with Locator, using Flutter get_it.

    Create a UserService with a cached data if you like:

    class UserService {
      final Firestore _db = Firestore.instance;
      final String _collectionName = 'users';
      CollectionReference _ref;
    
      User _cachedUser; //<----- Cached Here
    
      UserService() {
        this._ref = _db.collection(_collectionName);
      }
    
      User getCachedUser() {
        return _cachedUser;
      }
    
      Future getUser(String id) async {
        DocumentSnapshot doc = await _ref.document(id).get();
    
        if (!doc.exists) {
          log("UserService.getUser(): Empty companyID ($id)");
          return null;
        }
    
        _cachedUser = User.fromDocument(doc.data, doc.documentID);
        return _cachedUser;
      }
    }
    

    Then create create a Locator

    GetIt locator = GetIt.instance;
    
    void setupLocator() {
      locator.registerLazySingleton(() => new UserService());
    }
    

    And instantiate in main()

    void main() {
      setupLocator();
      new Routes();
    }
    

    That's it! You can call your Service + cachedData everywhere using:

    .....
    UserService _userService = locator();
    
    @override
    void initState() {
      super.initState();
      _user = _userService.getCachedUser();
    }
    

提交回复
热议问题