Search code examples
fluttergeolocation

Flutter build not running with geocoding and location package


I tried to run a simple project but i gives me errors:

Launching lib\main.dart on ASUS Z01QD in debug mode...

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':app:processDebugResources'.
> Could not resolve all files for configuration ':app:debugRuntimeClasspath'.
   > Failed to transform play-services-base-16.0.1.aar (com.google.android.gms:play-services-base:16.0.1) to match attributes {artifactType=android-compiled-dependencies-resources, org.gradle.status=release}.
      > Execution failed for AarResourcesCompilerTransform: C:\Users\win\.gradle\caches\transforms-2\files-2.1\f260781842f212c36494d469961b4620\jetified-play-services-base-16.0.1.
         > AAPT2 aapt2-4.1.0-6503028-windows Daemon #0: Unexpected error during compile 'C:\Users\win\.gradle\caches\transforms-2\files-2.1\f260781842f212c36494d469961b4620\jetified-play-services-base-16.0.1\res\drawable-xhdpi-v4\common_google_signin_btn_text_dark_normal_background.9.png', attempting to stop daemon.
           This should not happen under normal circumstances, please file an issue if it does.
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 58s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

main.dart ->

import 'package:flutter/material.dart';
import 'package:locationflutter/splashscreen.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: SplashScreen(),
    );
  }
}

splashscreen.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:locationflutter/location_service.dart';
import 'package:locationflutter/mainscreen.dart';

class SplashScreen extends StatefulWidget {
  const SplashScreen({Key? key}) : super(key: key);

  @override
  _SplashScreenState createState() => _SplashScreenState();
}

class _SplashScreenState extends State<SplashScreen> {
  @override
  void initState() {
    super.initState();
    locationService();
  }

  Future<void> locationService() async {
    Location location = new Location();

    bool _serviceEnabled;
    PermissionStatus _permissionLocation;
    LocationData _locData;

    _serviceEnabled = await location.serviceEnabled();
    if(!_serviceEnabled) {
      _serviceEnabled = await location.requestService();
      if (!_serviceEnabled) {
        return;
      }
    }

    _permissionLocation = await location.hasPermission();
    if(_permissionLocation == PermissionStatus.denied) {
      _permissionLocation = await location.requestPermission();
      if(_permissionLocation != PermissionStatus.granted) {
        return;
      }
    }

    _locData = await location.getLocation();

    setState(() {
      UserLocation.lat = _locData.latitude!;
      UserLocation.long = _locData.longitude!;
    });

    Timer(Duration(milliseconds: 500), () {
      Navigator.pushReplacement(context,
          MaterialPageRoute(builder: (context) => MainScreen()));
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Text("WELCOME"),
      ),
    );
  }
}

mainscreen.dart

import 'package:flutter/material.dart';
import 'package:geocoding/geocoding.dart';
import 'package:locationflutter/location_service.dart';

class MainScreen extends StatefulWidget {
  const MainScreen({Key? key}) : super(key: key);

  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreen> {
  String country = '';
  String name = '';
  String street = '';
  String postalCode = '';

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

    getLocation();
  }

  Future<void> getLocation() async {
    List<Placemark> placemark = await placemarkFromCoordinates(UserLocation.lat, UserLocation.long);

    print(placemark[0].country);
    print(placemark[0].name);
    print(placemark[0].street);
    print(placemark[0].postalCode);

    setState(() {
      country = placemark[0].country!;
      name = placemark[0].name!;
      street = placemark[0].street!;
      postalCode = placemark[0].postalCode!;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Lat : " + "${UserLocation.lat}"),
            Text("Long : " + "${UserLocation.long}"),
            Text("Country : " + "$country"),
            Text("Name : " + "$name"),
            Text("Street : " + "$street"),
            Text("PostalCode : " + "$postalCode"),
          ],
        ),
      ),
    );
  }
}

location_service.dart

class UserLocation {
  static double lat = 0;
  static double long = 0;
}

pubspec.yaml

name: locationflutter
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
version: 1.0.0+1

environment:
  sdk: ">=2.12.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  location: ^4.3.0
  geocoding: ^2.0.1
  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2

dev_dependencies:
  flutter_test:
    sdk: flutter

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware.

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

flutter doctor

Doctor summary (to see all details, run flutter doctor -v):
[√] Flutter (Channel stable, 2.8.1, on Microsoft Windows [Version 10.0.19043.1415], locale
    en-US)
[√] Android toolchain - develop for Android devices (Android SDK version 32.0.0)
[√] Chrome - develop for the web
[√] Visual Studio - develop for Windows (Visual Studio Community 2022 17.0.4)
[√] Android Studio (version 2020.3)
[√] VS Code (version 1.63.2)
[√] Connected device (4 available)
    ! Device 127.0.0.1:5555 is offline.

• No issues found!

I don't know what am I doing wrong.


Solution

  • I Fixed this issue by:

    In gradle-wrapper.properties I defined Gradle version 6.1.1
    by adding at the last of the file
    distributionUrl=https://services.gradle.org/distributions/gradle-6.1.1-all.zip

    And in the project-level build.gradle I set version 4.0.2
    by adding
    classpath 'com.android.tools.build:gradle:4.0.2'

    reference: solution