如何监听使用 getit 包扩展 changeNotifer 的单例 class 的变化?

How to listen to changes of a singleton class that extends changeNotifer with getit package?

我正在使用来自 flutter 的 getit 包。如何监听使用 getit 包扩展 changeNotifer 的单例 class 的变化?

class UserService extends ChangeNotifier {
 Database _db = serviceLocator<Database>();

  User user;

  Future<void> loadUserFromDatabase(String userId) async {
    User user = await _db.getUser(userId);

      if (user != null) {
        updateUser(user: user);
      }
  }

  void updateUser({
    User user,
  }) {
    this.user = user;
    notifyListeners();
  }
}


// SERVICE LOCATOR
GetIt serviceLocator = GetIt.instance;

void setupServiceLocator() {
 serviceLocator.registerLazySingleton<Database>(
    () => DatabaseImpl(),
  );
  serviceLocator.registerLazySingleton<UserService>(
    () => UserService(),
  );
}

class UserDetailsPage extends StatelessWidget {
  final _service = serviceLocator<UserService>();

  @override
  Widget build(BuildContext context) {
    return return Container(
        padding: const EdgeInsets.all(8.0),
        child: Text(
              _service.user != null
                  ? _service.user.name
                  : "",
            ),
     );
  }

上述代码中,如何将name的变化反映到UserDetailsPage中?

您可以使用StatefullWidget来实现您的需求,方便更新详情页。

添加侦听器并在每次更新时通知小部件。

class UserDetailsPage extends StatefulWidget {
  @override
  _UserDetailsPageState createState() => _UserDetailsPageState();
}

class _UserDetailsPageState extends State<UserDetailsPage> {
  final _service = serviceLocator<UserService>();
  
  void initState(){
    super.initState();
    _service?.addListener(updateUserDetails);
  }

  void updateUserDetails(){
    setState((){});
  }
  
  @override
  Widget build(BuildContext context) {
    return return Container(
      padding: const EdgeInsets.all(8.0),
      child: Text(
        userService.user != null
            ? _service.user.name
            : "",
      ),
    );
  }
}