Flutter Provider与Workmanager整合

3

我使用Provider 结合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,

      };
}

请提供一个最小可复现示例 - rckrd
1个回答

0
创建并保持 Auth 对象,以便您可以从 callbackDispatcher 和小部件树中访问它。例如,使用单例或类似的东西。然后在 Flutter 小部件树中,您可以使用 {{link1:Provider.value 来公开 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()));
}

我无法访问当前数据(用户实例)为空 @rckrd - SAWA Group
那么 data 应该从哪里来呢?这似乎与原问题无关。 - rckrd
从API获取的日期用户并在提供程序中创建新实例,数据通知来自Pusher Broadcast,我正确获取了数据,但我需要更新提供程序中当前用户的通知,我无法从callbackDispatcher访问当前登录用户。 - SAWA Group
你需要提供更多的上下文让我理解。在你上面的代码中,只有在调用Login之前,Auth中的user才会为空。 - rckrd

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接