Workmanager don't show printing geodata using geolocator

34 views Asked by At

I have the following problem. The task is as follows: When I click on the button, I need to run a background task to get the user's geo data. Here is the current application code

import 'dart:async';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:workmanager/workmanager.dart';


void getLocationUpdates() async {

  try {
    Position position = await Geolocator.getCurrentPosition(
      desiredAccuracy: LocationAccuracy.best,
    );

    stderr.writeln("[SUCCES] GEO POSITION TASK:");
    stderr.writeln("Latitude: ${position.latitude}, Longitude: ${position.longitude}");
  } catch (e) {
    stderr.writeln("[ERROR] Error fetching from workmanager location: $e");
  }
}

void callbackDispatcherTask() {
  Workmanager().executeTask((taskName, inputData) {
    getLocationUpdates();
    print("Task $taskName was executed");
    return Future.value(true);
  });
}


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Workmanager().initialize(
      callbackDispatcherTask,
      isInDebugMode: true
  );
  runApp(MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _locationMessage = '';

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }


  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Geolocator Example'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Icon(Icons.location_on, size: 50),
              SizedBox(height: 10),
              Text(
                'Your Current Location is:',
                style: TextStyle(fontSize: 20),
              ),
              SizedBox(height: 5),
              Text(
                _locationMessage,
                style: TextStyle(fontSize: 16),
              ),
              TextButton(
                  onPressed: () {
                    Workmanager().registerOneOffTask("uniqueTaskName", "GEOPOS TAG",
                    inputData: <String, dynamic>{});
                  },
                  child: Text("Start task"))
            ],
          ),
        ),
      ),
    );
  }
}

The problem is that when successfully running await Geolocator.getCurrentPosition print, stderr.writeln, etc. do not show the user's current position. Here is a screenshot with a deliberate mistake, for example, did not provide permission:

enter image description here

And here's a screenshot if everything is fine, but i dont get info:

enter image description here

Please explain why workmanager does not show geo position data, but it shows errors

AndroidManifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android">

    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION"/>

    <application
        android:label="vniira"
        android:name="${applicationName}"
        android:icon="@mipmap/ic_launcher">
        <activity
            android:name=".MainActivity"
            android:exported="true"
            android:launchMode="singleTop"
            android:theme="@style/LaunchTheme"
            android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
            android:hardwareAccelerated="true"
            android:windowSoftInputMode="adjustResize">
            <!-- Specifies an Android theme to apply to this Activity as soon as
                 the Android process has started. This theme is visible to the user
                 while the Flutter UI initializes. After that, this theme continues
                 to determine the Window background behind the Flutter UI. -->
            <meta-data
              android:name="io.flutter.embedding.android.NormalTheme"
              android:resource="@style/NormalTheme"
              />
            <intent-filter>
                <action android:name="android.intent.action.MAIN"/>
                <category android:name="android.intent.category.LAUNCHER"/>
            </intent-filter>
        </activity>
        <!-- Don't delete the meta-data below.
             This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
        <meta-data
            android:name="flutterEmbedding"
            android:value="2" />
    </application>
</manifest>

pubshpeck.yml:

dependencies:
  flutter:
    sdk: flutter

  geolocator: ^11.0.0
  workmanager: ^0.5.2
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

I tried to remove await, and use then callBack. Not worked

0

There are 0 answers