Flutter WorkManager报“无法解析主入口函数”及FlutterJNI警告排查
Flutter WorkManager初始化报错及后台数据同步问题
问题描述
我尝试在Flutter应用中使用WorkManager实现后台任务,当设备联网时将离线保存的用户数据同步至在线数据库。但初始化WorkManager并运行应用后,日志中出现了错误及FlutterJNI相关警告。
软件配置
- Java:17.0.11
- Flutter:3.29.0
- Android Studio:2024.2.1 Patch 3
错误日志
: FlutterJNI.loadLibrary called more than once I/ResourceExtractor(13363): Found extracted resources res_timestamp-1-1741615888564 W/FlutterJNI(13363): FlutterJNI.prefetchDefaultFontManager called more than once W/FlutterJNI(13363): FlutterJNI.init called more than once E/flutter (13363): [ERROR:flutter/runtime/dart_isolate.cc(869)] Could not resolve main entrypoint function. E/flutter (13363): [ERROR:flutter/runtime/dart_isolate.cc(170)] Could not run the run main Dart entrypoint. E/flutter (13363): [ERROR:flutter/runtime/runtime_controller.cc(557)] Could not create root isolate. E/flutter (13363): [ERROR:flutter/shell/common/shell.cc(668)] Could not launch engine with configuration. I/Choreographer(13363): Skipped 74 frames! The application may be doing too much work on its main thread. I/flutter (13363): Initializing WorkManager... I/flutter (13363): WorkManager initialized successfully. I/flutter (13363): 📂 List of Databases: I/flutter (13363): 📌 Database Found: /data/user/0/com.example.test_app/app_flutter/app.db I/flutter (13363): Users in database: I/flutter (13363): ID: 1, Name: raj, Job: worker, Synced: false I/flutter (13363): ID: 2, Name: robjn, Job: seeker, Synced: false I/flutter (13363): ID: 3, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 4, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 5, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 6, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 7, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 8, Name: Raj, Job: Engineer, Synced: false I/flutter (13363): ID: 9, Name: Ravi, Job: Tailor, Synced: false I/flutter (13363): ID: 10, Name: Ragul, Job: Sailor, Synced: false
相关代码
Main.dart
void main() async { WidgetsFlutterBinding.ensureInitialized(); await WorkManagerService.initialize(); final database = AppDatabase(); await database.listAllDatabases(); final users = await database.getAllUsers(); print("Users in database:"); for (var user in users) { print( "ID: ${user.id}, Name: ${user.name}, Job: ${user.job}, Synced: ${user.isSynced}"); } runApp(const ProviderScope(child: MyApp())); }
TestAddUserProvider.dart
final addTestUserProvider = StateNotifierProvider<AddTestUserProvider, AsyncValue<User?>>((ref) { final database = ref.watch(databaseProvider); return AddTestUserProvider(database); }); class AddTestUserProvider extends StateNotifier<AsyncValue<User?>> { final AppDatabase _database; AddTestUserProvider(this._database) : super(const AsyncValue.data(null)); Future<void> addUser(String name, String job, bool bool) async { state = const AsyncValue.loading(); print("offline"); await _addUserOffline(name, job); } Future<void> _addUserOffline(String name, String job) async { try { final newUser = UsersCompanion( name: Value(name), job: Value(job), isSynced: const Value(false), ); await _database.insertUser(newUser); WorkManagerService.registerSyncTask(); state = const AsyncValue.data(null); } catch (e, stackTrace) { state = AsyncValue.error(e, stackTrace); } } }
work_manager.dart
import 'package:flutter_riverpod/flutter_riverpod.dart'; import 'package:workmanager/workmanager.dart'; import '../data/providers/user_provider.dart'; import '../database/app_database.dart'; import '../utils/constants.dart'; import 'api_service.dart'; import 'network_service.dart'; const String syncTask = "sync_offline_users"; class WorkManagerService { static Future<void> initialize() async { print("Initializing WorkManager..."); Workmanager().initialize( _callbackDispatcher, isInDebugMode: true, ); print("WorkManager initialized successfully."); } static void registerSyncTask() { print("Registering sync task..."); Workmanager().registerOneOffTask( "sync_users_task", syncTask, constraints: Constraints( networkType: NetworkType.connected, ), ); print("Sync task registered successfully."); } @pragma('vm:entry-point') static void _callbackDispatcher() { Workmanager().executeTask((task, inputData) async { print("Executing task: $task"); final container = ProviderContainer(); try { final database = container.read(databaseProvider); final apiService = container.read(apiServiceProvider); final isConnected = container.read(connectivityServiceProvider).isConnectedSync(); if (task == syncTask && isConnected) { await _syncOfflineUsers(database, apiService); } } catch (e) { print("Error in callback dispatcher: $e"); } finally { container.dispose(); } return Future.value(true); }); } static Future<void> _syncOfflineUsers( AppDatabase database, ApiService apiService) async { print("Starting to sync offline users..."); final unsyncedUsers = await database.getUnsyncedUsers(); print("Fetched ${unsyncedUsers.length} unsynced users."); for (var user in unsyncedUsers) { print("Syncing user: ${user.name} (ID: ${user.id})"); try { final response = await apiService.post( addUsersEndpoint, body: {"name": user.name, "job": user.job}, ); print("API response received: $response"); if (response != null && response['id'] != null) { print( "User ${user.name} synced successfully with ID: ${response['id']}"); await database.markUserAsSynced(user.id, response['id']); print("User marked as synced in the database."); } else { print( "API response is null or missing ID. Sync failed for user ${user.id}."); } } catch (e) { print("Failed to sync user ${user.id}: $e"); } } print("Offline user sync completed."); } }
AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <meta-data android:name="flutterEmbedding" android:value="2" /> <service android:name="MyJobService" android:permission="android.permission.BIND_JOB_SERVICE" android:exported="true"> </service>
复现方式
- 使用项目中的test_screen.dart和test_provider复现问题,离线保存逻辑已单独分离。
内容的提问来源于stack exchange,提问作者Vishnu Kumar
相关产品推荐
相关产品推荐

