Flutter:将后台服务分离到不同的类,导致方法错误



嗨,所以我试图使用background_service为我的应用程序使用flutter_background_service插件,我已经设法遵循文档中的例子,我想把这些函数移动到不同的类更好的代码编写。问题是,当我将它移动到另一个文件并调用该方法时,它显示了一个错误:

未处理异常:onStart方法必须是顶级函数或静态函数

是什么导致了这种情况的发生?谁能解释一下,怎么修理它?我如何让我的background_service应用程序监听我的firestore数据…我想检测是否有任何任务几乎超过due_date。

下面是我的代码:Main.dart
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await BackgroundService().initializeService();
}

Background_service.dart

class BackgroundService {
static const notificationChannelId = 'my_foreground';
static const notificationId = 888;
Future<void> initializeService() async {
final service = FlutterBackgroundService();
const AndroidNotificationChannel channel = AndroidNotificationChannel(
notificationChannelId, // ID
'MY FOREGROUND SERVICE', // Title
description:
'This channel is used for important notifications.', // Description
importance: Importance.low, // importance must be at low or higher level
);
final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
if (Platform.isIOS) {
await flutterLocalNotificationsPlugin.initialize(
const InitializationSettings(
iOS: IOSInitializationSettings(),
),
);
}
await flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
AndroidFlutterLocalNotificationsPlugin>()
?.createNotificationChannel(channel);
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
autoStart: true,
isForegroundMode: true,
),
iosConfiguration: IosConfiguration(
autoStart: true,
onForeground: onStart,
onBackground: _onIosBackground,
),
);
service.startService();
}
onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();

/// Code about _onstrat method
}
@pragma('vm:entry-point')
Future<bool> _onIosBackground(ServiceInstance service) async {
/// Code about Ios background
}
}

顶层意味着函数应该位于任何类或函数的层次结构。

必须将函数放在类的外部。阅读这里的文档:https://dart.dev/guides/language/effective-dart/design#avoid-defining-a-class-that-contains-only-static-members

  • 处理:

background_service.dart

// on start is a top-level function
@pragma('vm:entry-point') 
onStart(ServiceInstance service) async {
DartPluginRegistrant.ensureInitialized();

/// Code about _onstrat method
}
// top-level function
@pragma('vm:entry-point')
Future<bool> _onIosBackground(ServiceInstance service) async {
/// Code about Ios background
}

class BackgroundService {
static const notificationChannelId = 'my_foreground';
static const notificationId = 888;
......
await service.configure(
androidConfiguration: AndroidConfiguration(
onStart: onStart,
),
iosConfiguration: IosConfiguration(
onForeground: onStart,
onBackground: _onIosBackground,
),
.......

相关内容

最新更新