带有 Workmanager 的 Flutter Provider

Flutter Provider with Workmanager

我用Provider with Workmanager

Workmanager 对于 运行 周期性任务特别有用,例如定期获取远程数据。

我使用 Workmanager 在后台获取通知

但是当我收到通知时我需要方法我需要 Provider 中的调用函数但我没有上下文

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
    -->//// Code to get Notification from MY web get newNotificationData
     Provider.of<Auth>(context, listen: false).update_notification(newNotificationData);
    return Future.value(true);
  });
}

void main() {
  Workmanager().initialize(
    callbackDispatcher, // The top level function, aka callbackDispatcher
    isInDebugMode: true // If enabled it will post a notification whenever the task is running. Handy for debugging tasks
  );
  Workmanager().registerOneOffTask("1", "simpleTask"); //Android only (see below)
  runApp(MyApp());
}

更新 我需要更新当前用户 授权

    class Auth extends ChangeNotifier {
      bool _isLoggedIn = false;
      User? _user;
     void update_notification(newNotificationData){
       this._user!.notification.add(newNotificationData);
      }
      void Login(username,password){
       //// Code to login and get UserData
         this._isLoggedIn = true;
         this._user = User.fromJson(data);
      }
    }

用户模型

class User {
  User(
      {required this.id,
       required this.username,
      required this.fullName,
      required this.email,
      required this.notification});
  User.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        username = json['username'],
        fullName = json['fullName'],
        email = json['email'],
        notification = json['notification'];
  final int id;
  final String username;
  final String fullName;
  final String email;

  List<dynamic> notification;

  Map<String, dynamic> toJson() => {
        'id': id,
        'username': username,
        'fullName': fullName,
        'email': email,
        'notification': notification,

      };
}

创建并保存 Auth 对象,您可以从 callbackDispatcher 和小部件树访问它。例如使用单例或类似的东西。然后在 flutter widget 树中你可以使用 Provider.value to expose Auth..

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
    Auth.instance.update_notification(newNotificationData);
    return Future.value(true);
  });
}

void main() {
  Workmanager().initialize(
    callbackDispatcher,
    isInDebugMode: true
  );
  runApp(ChangeNotifierProvider.value(
         value: Auth.instance, // Same object as above
         child: MyApp()));
}