easazade / android_long_task

android long task is a flutter plugin to run dart code in an android foreground service with simplicity
Apache License 2.0
16 stars 6 forks source link

Dart Unhandled Exception: NoSuchMethodError: No top-level getter 'serviceMain' declared. #7

Closed Eimji closed 2 years ago

Eimji commented 2 years ago

Hello

Running the example with flutter run --release gives this error

E/flutter (14495): [ERROR:flutter/shell/common/shell.cc(94)] Dart Unhandled Exception: NoSuchMethodError: No top-level getter 'serviceMain' declared.
E/flutter (14495): Receiver: top-level
E/flutter (14495): Tried calling: serviceMain, stack trace: #0      NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:218)
E/flutter (14495): 
E/flutter (14495): [ERROR:flutter/runtime/dart_isolate.cc(707)] Could not resolve main entrypoint function.
E/flutter (14495): [ERROR:flutter/runtime/dart_isolate.cc(191)] Could not run the run main Dart entrypoint.
E/flutter (14495): [ERROR:flutter/runtime/runtime_controller.cc(382)] Could not create root isolate.
E/flutter (14495): [ERROR:flutter/shell/common/shell.cc(574)] Could not launch engine with configuration.

The code only works in debug mode. This is very weird, the code worked well a few weeks ago. It seems to be an issue related to Flutter https://github.com/flutter/flutter/issues/91841 I don't know how to fix the issue, which is a severe regression.

Could you confirm the issue please? and help me to find a workaround.

Thanks

easazade commented 2 years ago

hi @Eimji I'll check it out

easazade commented 2 years ago

@Eimji I faced the same problem. but apparently I forgot to annotate the serviceMain function in /example with @pragma('vm:entry-point'). I added the annotation and reran the example in release mode. it runs fine. please pull from master and confirm. it should be fine.

Also checked the issue i don't think it should cause this plugin a problem

Eimji commented 2 years ago

Thanks @easazade You are right! when annoting with @pragma('vm:entry-point'), your example code works.

Anyway, I have already annoted the ServiceMain in my application code (thanks for your great package). My code worked without any issue a few weeks ago. After upgrading Flutter this week, my code doesn't work anymore. I have tried to downgrade Flutter to previous versions, but no success :( Still this error Dart Unhandled Exception: NoSuchMethodError: No top-level getter 'serviceMain' declared.

As I also use Firebase Cloud Messaging with a top-level function for handling notifications in background, my issue seems to be related to flutter/flutter#91841 So waiting for answer there

Eimji commented 2 years ago

I finally managed to solve my issue. I uninstalled Flutter and reinstalled it again, after running flutter clean, my code works again.

Thanks for motivating me to find the solution!

easazade commented 2 years ago

happy that your problem is solved @Eimji

kazbeksultanov commented 2 years ago

Hi, I am experiencing exact the same issue as @Eimji. I placed @pragma('vm:entry-point') but there is weird behavior that everything works great in debug mode, no mistakes at all. But in profile or release mode, always the same problem. I don't know why this happening. I don't have any clue why it is so. Any ideas?

D/PathProviderPlugin(27947): Use TaskQueues. E/flutter (27947): [ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: NoSuchMethodError: No top-level getter 'serviceMain' declared. E/flutter (27947): Receiver: top-level E/flutter (27947): Tried calling: serviceMain, stack trace: #0 NoSuchMethodError._throwNew (dart:core-patch/errors_patch.dart:222) E/flutter (27947): E/flutter (27947): [ERROR:flutter/runtime/dart_isolate.cc(681)] Could not resolve main entrypoint function. E/flutter (27947): [ERROR:flutter/runtime/dart_isolate.cc(165)] Could not run the run main Dart entrypoint. E/flutter (27947): [ERROR:flutter/runtime/runtime_controller.cc(381)] Could not create root isolate. E/flutter (27947): [ERROR:flutter/shell/common/shell.cc(580)] Could not launch engine with configuration.

[✓] Flutter (Channel stable, 2.10.3, on macOS 11.5.2 20G95 darwin-x64, locale ru) • Flutter version 2.10.3 at /Users/kazbek/flutter • Upstream repository https://github.com/flutter/flutter.git • Framework revision 7e9793dee1 (7 days ago), 2022-03-02 11:23:12 -0600 • Engine revision bd539267b4 • Dart version 2.16.1 • DevTools version 2.9.2

[✓] Android toolchain - develop for Android devices (Android SDK version 31.0.0) • Android SDK at /Users/kazbek/Library/Android/sdk/ • Platform android-31, build-tools 31.0.0 • Java binary at: /Users/kazbek/Library/Java/JavaVirtualMachines/corretto-1.8.0_322/Contents/Home/bin/java • Java version OpenJDK Runtime Environment Corretto-8.322.06.1 (build 1.8.0_322-b06) • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 13.2.1) • Xcode at /Applications/Xcode.app/Contents/Developer • CocoaPods version 1.11.2

[✓] Chrome - develop for the web • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2021.1) • Android Studio at /Applications/Android Studio.app/Contents • Flutter plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/9212-flutter • Dart plugin can be installed from: 🔨 https://plugins.jetbrains.com/plugin/6351-dart • Java version OpenJDK Runtime Environment (build 11.0.11+0-b60-7590822)

[✓] VS Code (version 1.63.2) • VS Code at /Applications/Visual Studio Code.app/Contents • Flutter extension version 3.29.0

[✓] Connected device (2 available) • SM A415F (mobile) • R58NC2JVXVY • android-arm64 • Android 11 (API 30) • Chrome (web) • chrome • web-javascript • Google Chrome 99.0.4844.51

[✓] HTTP Host Availability • All required HTTP hosts are available

• No issues found!

easazade commented 2 years ago

hi @kazbeksultanov. I'll check with the your flutter version see if i get the same error . have you tried what @Eimji suggested above?

kazbeksultanov commented 2 years ago

To reinstall flutter again? It didn't help me. Exact same error

easazade commented 2 years ago

@kazbeksultanov which version are you using?

kazbeksultanov commented 2 years ago

[✓] Flutter (Channel stable, 2.10.3, on macOS 11.5.2 20G95 darwin-x64, locale ru)

easazade commented 2 years ago

library version i meant

kazbeksultanov commented 2 years ago

0.4.8 not. Ooo I did not notice you have updated package? I will try with new version

kazbeksultanov commented 2 years ago

With 1.0.0 version again the same error.

Working in debug mode and not in profile

easazade commented 2 years ago

I just recreated the example project and ran it with flutter and dart version you provided. I didn't get any error.

easazade commented 2 years ago

could you copy the entire content of you main.dart file in here

kazbeksultanov commented 2 years ago

Main.dart

import 'dart:async';

import 'package:android_long_task/android_long_task.dart';
import 'package:dio/dio.dart';
import 'package:drivers/api/dio_client.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:optional/optional.dart';
import 'package:solai_driver/layers/adapters/adapter.dart';
import 'package:solai_driver/layers/services/api/access_token.dart';
import 'package:solai_driver/layers/services/api/impl/gateway.dart';
import 'package:solai_driver/layers/services/api/schemes.dart';

import 'app/configs.dart';
import 'app/pages/main_app/page.dart';
import 'layers/pages/splash_screen/ui/page.dart';
import 'layers/services/impl/gps_tracker_impl.dart';`

@pragma('vm:entry-point')
Future<void> serviceMain() async {
  WidgetsFlutterBinding.ensureInitialized();

  ServiceClient.setExecutionCallback((initialData) async {
    debugPrint('-------->>>>>>  serviceMain started');
    AppServiceData serviceData = AppServiceData.fromJson(initialData);
    final _api = ApiGatewayImpl(DioClient(Dio(), baseEndpoint: serviceData.baseEndpoint));
    final session = AccessTokenSession(serviceData.accessToken).toOptional;
    final _interval = Duration(seconds: serviceData.intervalSec);
    int total = 0;
    int successNum = 0;
    int saveNum = 0;
    Position? p;
    TaskPerformanceRequest? request;
    while (true) {
      total++;
      final d1 = DateTime.now();
      try {
        p = await Geolocator.getCurrentPosition();
      } catch (_) {}
      if (p == null) {
        continue;
      }
      request = Adapter.model.toTaskPerformanceReq(
        dateTime: DateTime.now(),
        p: p,
        driverClientDbId: serviceData.driverClientDbId,
        routingSolutionId: serviceData.routingSolutionId,
        assignmentTaskId: serviceData.assignmentTaskId,
      );
      bool responseBool = false;
      try {
        responseBool = await _api.sendTaskPerformance(request, session: session);
      } catch (_) {}
      if (responseBool) {
        successNum++;
        serviceData.request = null;
      } else {
        saveNum++;
        serviceData.request = request;
      }

      serviceData.notificationDescriptionText =
          'Т: $total, Ус: $successNum, Cохр.: $saveNum, taskId: ${serviceData.assignmentTaskId}, '
          'routingSolutionId: ${serviceData.routingSolutionId}, '
          'assignmentTaskId: ${serviceData.assignmentTaskId}, ';

      await ServiceClient.update(serviceData);
      final d2 = DateTime.now();
      final dur = _interval - d2.difference(d1);
      await Future.delayed(dur);
    }
  });
}

Future<void> main() async {
  await bootstrapApp(
    preDefConfFeat: PreDefConfFeat.test,
    app: () => const MainApp(
      home: SplashScreenProvider(),
    ),
  );
}
kazbeksultanov commented 2 years ago

I just run example project in new test application and there everything is fine. In debug and also in release mode. It's interesting why this happening. Seems like some other service is conflicting in registering isolate. I suspect gelocator, but don't know how to even identify it.

kazbeksultanov commented 2 years ago

Finally things worked. I followed this issue https://github.com/flutter/flutter/issues/91841 , and decided to check on master branch. Everything worked fine there.

easazade commented 2 years ago

Glad to hear it's working. thank your for reporting how you got it working. hopefully this flutter issue 91841 will get resolved in later releases of flutter

AbnikaGarg commented 1 month ago

kazbeksultanov please give me detailed solution