尝试在后台任务 Flutter 中检索时,Workmanager inputData 为空

问题描述 投票:0回答:1

我在 Flutter 的 Workmanager 中传递和检索 inputData 时遇到问题。我试图在注册任务时发送一些数据(如 id 和日期),但是当我尝试访问后台任务中的 inputData 时,我不断收到 null。

Workmanager().registerOneOffTask(
  "simpleTask", // Unique task name
  "simpleTask", // The task name
  tag: '1',
  inputData: {'id': '1', 'date': '16-10-2024'}, // Input data to be passed
);

void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) {
    print('Task name: $task');
    print('Input data: $inputData'); // This prints null
    print('Notification id: ${inputData?["id"]}');
    print('Notification date: ${inputData?["date"]}');
    return Future.value(true);
  });
}

Workmanager().initialize(
  callbackDispatcher,
  isInDebugMode: true // For debugging
);

Logs when Workmanager().executeTask call

flutter background flutter-workmanager
1个回答
0
投票

确保在注册任何任务之前初始化

Workmanager
,并确保您的 callbackDispatcher
 是用 
@pragma('vm:entry-point')
 注释的顶级函数。以下是调整代码的方法:

  1. 注册任务之前初始化Workmanager:

    Workmanager().initialize( callbackDispatcher, isInDebugMode: true, // For debugging ); Workmanager().registerOneOffTask( "simpleTask", // Unique task name "simpleTask", // The task name tag: '1', inputData: {'id': '1', 'date': '16-10-2024'}, // Input data to be passed );
    
    
  2. callbackDispatcher

     注释你的 
    @pragma('vm:entry-point')
     并确保它是顶级函数:

    @pragma('vm:entry-point') void callbackDispatcher() { Workmanager().executeTask((task, inputData) { print('Task name: $task'); print('Input data: $inputData'); // This should now print the inputData print('Notification id: ${inputData?["id"]}'); print('Notification date: ${inputData?["date"]}'); return Future.value(true); }); }
    
    
通过在注册任务之前初始化

Workmanager

 并正确注释 
callbackDispatcher
,您应该能够在后台任务中访问 
inputData

© www.soinside.com 2019 - 2024. All rights reserved.