fluttercommunity / flutter_workmanager

A Flutter plugin which allows you to execute code in the background on Android and iOS.
826 stars 247 forks source link

🐞[Cannot Call Future Function on the Callback] #476

Closed muhAzri closed 1 year ago

muhAzri commented 1 year ago

Version

Technology Version
Workmanager version 0.5.1

Describe the error So i want to call the async function on the callback but it always error when i use but when i run the function normaly outside the callback its working really fine

When i uncomment the await function and change it with like print it run well the error only caused when there is await function on it

this is the callback Code

@pragma('vm:entry-point')
void callbackDispatcher() {
  Workmanager().executeTask((task, inputData) async {
    String phoneNumber = inputData?['phone_number'];

    switch (task) {
      case 'Fetch Wallpaper':
        await wallpaperChangerHelper(phoneNumber);
        break;
    }

    return Future.value(true);
  });
}

the void main:

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  DartPluginRegistrant.ensureInitialized();

  await Workmanager().initialize(
      callbackDispatcher, 
      isInDebugMode:
          true 
      );

  HydratedBloc.storage = await HydratedStorage.build(
    storageDirectory: await getApplicationDocumentsDirectory(),
  );

  await dotenv.load(fileName: ".env");

  runApp(const MyApp());
}

the Helper Code:

import 'dart:io';

import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_dotenv/flutter_dotenv.dart';
import 'package:wallpaper_manager_flutter/wallpaper_manager_flutter.dart';

Future<void> wallpaperChangerHelper(String phoneNumber) async {
  var endpoint = dotenv.env['API_URL'];
  String finalUrl = '$endpoint$phoneNumber';

  try {
    File cachedimage = await DefaultCacheManager().getSingleFile(finalUrl);

    await WallpaperManagerFlutter().setwallpaperfromFile(
      cachedimage,
      WallpaperManagerFlutter.BOTH_SCREENS,
    );
  } catch (e) {
    rethrow;
  }
}

Button :

CustomButton(
            isPhoneNumberSet: widget.state.isPhoneSetted,
            action: () async {
              DartPluginRegistrant.ensureInitialized();

              context
                  .read<PhoneNumberCubit>()
                  .setPhoneNumber(phoneNumberController.text);

              await Workmanager().registerPeriodicTask(
                "fetch-wallpaper",
                "Fetch Wallpaper",
                frequency: const Duration(minutes: 15),
                inputData: {
                  'phone_number': phoneNumberController.text,
                },
              );
            },
          ),

Output of flutter doctor -v

    • Flutter version 3.10.0 on channel stable at /Users/muhammadazrifatihahsusanto/Development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 84a1e904f4 (2 weeks ago), 2023-05-09 07:41:44 -0700
    • Engine revision d44b5a94c9
    • Dart version 3.0.0
    • DevTools version 2.23.1

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.1)
    • Android SDK at /Users/muhammadazrifatihahsusanto/Library/Android/sdk
    • Platform android-33, build-tools 33.0.1
    • ANDROID_HOME = /Users/muhammadazrifatihahsusanto/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.6+0-17.0.6b802.4-9586694)
    • All Android licenses accepted.

[✓] Xcode - develop for iOS and macOS (Xcode 14.2)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 14C18
    • CocoaPods version 1.12.0

[✗] Chrome - develop for the web (Cannot find Chrome executable at /Applications/Google Chrome.app/Contents/MacOS/Google
    Chrome)
    ! Cannot find Chrome. Try setting CHROME_EXECUTABLE to a Chrome executable.

[✓] Android Studio (version 2022.2)
    • 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 17.0.6+0-17.0.6b802.4-9586694)

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

[✓] Connected device (2 available)
    • sdk gphone64 arm64 (mobile) • emulator-5554 • android-arm64 • Android 13 (API 33) (emulator)
    • macOS (desktop)             • macos         • darwin-arm64  • macOS 13.2.1 22D68 darwin-arm64

[✓] Network resources
    • All expected network resources are available.
muhAzri commented 1 year ago

Solved by load the env again on the helper