Flutter Google maps not loading because of asynchronous suspension - flutter

I am building an app in Flutter. I tried incorporating google maps into the app, but I can't see map on the emulator, as well as real device. I can see the google logo down on the screen and also zoom options can be seen. I have enabled maps sdk for android in google console. Also, I have added meta data required before activity tag.
My dart file displaying maps:
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class Home extends StatefulWidget {
const Home({super.key});
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
static const LatLng _kMapCenter =
LatLng(19.018255973653343, 72.84793849278007);
static const CameraPosition _kInitialPosition =
CameraPosition(target: _kMapCenter, zoom: 11.0, tilt: 0, bearing: 0);
late GoogleMapController _controller;
Future onMapCreated(GoogleMapController controller) async {
_controller = controller;
String value = await DefaultAssetBundle.of(context)
.loadString('assets/map_style.json');
_controller.setMapStyle(value);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Google Maps Demo'),
),
body: GoogleMap(
initialCameraPosition: _kInitialPosition,
onMapCreated: onMapCreated,
),
);
}
}
My debug console:
Restarted application in 1,719ms.
E/Surface (14290): getSlotFromBufferLocked: unknown buffer: 0xe81e0710
I/AssistStructure(14290): Flattened final assist data: 376 bytes, containing 1 windows, 3 views
D/MapsInitializer(14290): preferredRenderer: null
D/zzcb (14290): preferredRenderer: null
I/Google Maps Android API(14290): Google Play services package version: 224617040
I/Google Maps Android API(14290): Google Play services maps renderer version(legacy): 203115000
I/PlatformViewsController(14290): Using hybrid composition for platform view: 0
E/GoogleMapController(14290): Cannot enable MyLocation layer as location permissions are not granted
E/EGL_emulation(14290): eglQueryContext 32c0 EGL_BAD_ATTRIBUTE
E/EGL_emulation(14290): tid 14290: eglQueryContext(2019): error 0x3004 (EGL_BAD_ATTRIBUTE)
D/HostConnection(14290): HostConnection::get() New Host Connection established 0xb73d0620, tid 14683
D/HostConnection(14290): HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_YUV_Cache ANDROID_EMU_has_shared_slots_host_memory_allocator ANDROID_EMU_sync_buffer_data ANDROID_EMU_read_color_buffer_dma GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_host_side_tracing ANDROID_EMU_gles_max_version_3_0
D/EGL_emulation(14290): eglCreateContext: 0xa9c85870: maj 1 min 0 rcv 1
2
D/EGL_emulation(14290): eglMakeCurrent: 0xa9c85870: ver 1 0 (tinfo 0xa8476730) (first time)
E/flutter (14290): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Unable to load asset: assets/map_style.json
E/flutter (14290): #0 PlatformAssetBundle.load
package:flutter/…/services/asset_bundle.dart:258
E/flutter (14290): <asynchronous suspension>
E/flutter (14290): #1 AssetBundle.loadString
package:flutter/…/services/asset_bundle.dart:83
E/flutter (14290): <asynchronous suspension>
E/flutter (14290): #2 _HomeState.onMapCreated
package:d4u/…/withcar/home.dart:22
E/flutter (14290): <asynchronous suspension>
E/flutter (14290):
I/com.example.d4(14290): NativeAlloc concurrent copying GC freed 18209(1181KB) AllocSpace objects, 0(0B) LOS objects, 49% free, 4065KB/8131KB, paused 3.627ms total 110.580ms
F/crash_dump32(14756): crash_dump.cpp:474] failed to attach to thread 161: Permission denied
I/com.example.d4(14290): Thread[3,tid=14299,WaitingInMainSignalCatcherLoop,Thread*=0xda884610,peer=0x132c0228,"Signal Catcher"]: reacting to signal 3
I/com.example.d4(14290):
I/com.example.d4(14290): Wrote stack traces to tombstoned
2
E/libprocessgroup(14290): set_timerslack_ns write failed: Operation not permitted
F/crash_dump32(14917): crash_dump.cpp:474] failed to attach to thread 161: Permission denied
E/libprocessgroup(14290): set_timerslack_ns write failed: Operation not permitted
Screenshot of screen displaying maps
I had problem with google maps showing grey screen at first, and I found out that it was because of the emulator doesn't support google maps. But in other emulator also, I can't see maps. I have attached the image of my screen. I also tried in real android device, but it gives the same result.

I believe this post will help you : click here
Here I provided a sample code which actually works on both my emulator and device
class Map extends StatefulWidget {
const Map({Key? key}) : super(key: key);
#override
State<Map> createState() => _MapState();
}
class _MapState extends State<Map> {
static const _initialCameraPosition = CameraPosition(
target: LatLng(13.660397, 100.525939),
zoom: 4,
);
late GoogleMapController _googleMapController;
Marker? _origin;
#override
void dispose() {
_googleMapController.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: GoogleMap(
myLocationButtonEnabled: false,
initialCameraPosition: _initialCameraPosition,
onMapCreated: (controller) => _googleMapController = controller,
markers: {
if (_origin != null) _origin!,
},
onTap: _addMarker,
),
floatingActionButtonLocation: FloatingActionButtonLocation.startFloat,
floatingActionButton: FloatingActionButton(
onPressed: () => _googleMapController.animateCamera(
CameraUpdate.newCameraPosition(_initialCameraPosition),
),
foregroundColor: Colors.black,
backgroundColor: Theme.of(context).primaryColor,
child: const Icon(Icons.center_focus_strong),
),
);
}
}

Related

Facebook rewarded ads integration in flutter app for both ios and android

I checked almost all the possibility for integrate the app with Facebook rewarded ads for my project.
I tried,
facebook_audience_network 1.0.1 : rewarded ads not supports for IOS in this package
audience_network 0.0.4 : Works in ios , But in android it throws an error.
easy_ads_flutter 1.0.6 : always shows the google ads only,
Due to the lack of knowledge I faced a ban from google regarding the ad count per time period, So I need an exact knowledge for integrate the facebook ad.
#In this code I have used the audience network package with a different version in the git,
audience network:
git:
url: https://github.com/marcellocamara/audience_network.git
ref: master
The above code is works in ios , But on android getting error.
Any suggestion is appreciated and I need to implement the facebook rewarded ad in ios and android. In meta documentation the exact documentation of the flutter is not yet to be found.
The error I got when running the app in android, while using the audience_network plugin is below,
D/NetworkSecurityConfig(21286): No Network Security Config specified, using platform default
I/Timeline(21286): Timeline: Activity_launch_request time:70399667
W/ActivityThread(21286): handleWindowVisibility: no activity for token android.os.BinderProxy#3f94727
D/ForceDarkHelper(21286): updateByCheckExcludeList: pkg: com.example.sample activity: com.facebook.ads.AudienceNetworkActivity#48f1a72
I/chatty (21286): uid=10447(com.example.sample) identical 2 lines
D/ForceDarkHelper(21286): updateByCheckExcludeList: pkg: com.example.sample activity: com.facebook.ads.AudienceNetworkActivity#48f1a72
D/RenderScript HIDL Adaptation(21286): IRenderScriptDevice::getService()
D/RenderScript HIDL Adaptation(21286): IRenderScriptDevice::getService() returned 0x71555f38a0
D/RenderScript HIDL Adaptation(21286): HIDL successfully loaded.
W/.example.sampl(21286): Accessing hidden method Landroid/media/AudioTrack;->getLatency()I (greylist, reflection, allowed)
I/ExoPlayerImpl(21286): Init b7cd089 [ExoPlayerLib/2.8.4] [beryllium, POCO F1, Xiaomi, 29]
W/.example.sampl(21286): Accessing hidden method Landroid/app/ActivityThread;->currentActivityThread()Landroid/app/ActivityThread; (greylist, reflection, allowed)
W/.example.sampl(21286): Accessing hidden field Landroid/app/ActivityThread;->mActivities:Landroid/util/ArrayMap; (greylist, reflection, allowed)
W/.example.sampl(21286): Accessing hidden field Landroid/app/ActivityThread$ActivityClientRecord;->paused:Z (greylist, reflection, allowed)
I/flutter (21286): 9001
I/flutter (21286): Ad could not be presented
W/VideoCapabilities(21286): Unsupported mime image/vnd.android.heic
W/VideoCapabilities(21286): Unsupported mime video/divx
W/VideoCapabilities(21286): Unsupported mime video/divx4
2
W/VideoCapabilities(21286): Unrecognized profile/level 0/3 for video/mpeg2
W/VideoCapabilities(21286): Unsupported mime video/x-ms-wmv
I/OMXClient(21286): IOmx service obtained
D/SurfaceUtils(21286): connecting to surface 0x71925dc010, reason connectToSurface
I/MediaCodec(21286): [OMX.qcom.video.decoder.avc] setting surface generation to 21796865
D/SurfaceUtils(21286): disconnecting from surface 0x71925dc010, reason connectToSurface(reconnect)
D/SurfaceUtils(21286): connecting to surface 0x71925dc010, reason connectToSurface(reconnect)
I/ExtendedACodec(21286): setupVideoDecoder()
I/ExtendedACodec(21286): Decoder will be in frame by frame mode
D/SurfaceUtils(21286): set up nativeWindow 0x71925dc010 for 1280x720, color 0x7fa30c06, rotation 0, usage 0x20002900
W/Gralloc3(21286): allocator 3.x is not supported
I/OMXClient(21286): IOmx service obtained
2
I/ACodec (21286): codec does not support config priority (err -2147483648)
W/ExtendedACodec(21286): Failed to get extension for extradata parameter
V/RenderScript(21286): Successfully loaded runtime: libRSDriver_adreno.so
D/ (21286): Successfully queried cache dir: /data/user_de/0/com.example.sample/code_cache
D/RenderScript(21286): Setting cache dir: /data/user_de/0/com.example.sample/code_cache
E/libc (21286): Access denied finding property "vendor.debug.trace.perf"
D/AudioTrack(21286): set(sessionID=0)
D/AudioTrack(21286): set(): streamType -1, sampleRate 44100, format 0x1, channelMask 0x3, frameCount 14144, flags #0, notificationFrames 0, sessionId 0, transferType 3, uid -1, pid -1
Here is the code throws error
import 'package:audience_network/audience_network.dart';
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
#override
void initState() {
AudienceNetwork.init(
testingId: "",
testMode: true,
iOSAdvertiserTrackingEnabled: true,
).then((value) {
print('AudienceNetwork init $value');
});
super.initState();
}
void _incrementCounter() {
final rewardedAd = RewardedAd(
RewardedAd.testPlacementId,
);
rewardedAd.listener = RewardedAdListener(
onLoaded: () {
rewardedAd.show();
},
onVideoComplete: () {
rewardedAd.destroy();
print('Video completed');
},
onError: (code, message) {
print(code);
print(message);
},
);
rewardedAd.load();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
just use the below package solved my issue
audience_network:
git:
url: https://github.com/varunkamanibosc/audience_network.git
ref: master

Flutter HTTPS Server on Mobile Phone

Hi I am trying to run a server locally on the device and access via a webview - but having issue accessing the files - specially te certs on the mobile device. Here is my code:
import 'dart:io';
import 'package:flutter/material.dart' hide Router;
import 'package:shelf/shelf.dart';
import 'package:shelf/shelf_io.dart';
import 'package:shelf_router/src/router.dart';
import 'package:webview_flutter/webview_flutter.dart';
Future<void> main() async {
await startServer();
runApp(const MyApp());
}
// Configure routes.
final _router = Router()
..get('/', _rootHandler)
..get('/www/<message>', _echoHandler);
Response _rootHandler(Request req) {
return Response.ok('Hello, World!\n');
}
Response _echoHandler(Request request) {
final message = request.params['message'];
return Response.ok('$message\n');
}
SecurityContext getSecurityContext() {
// Bind with a secure HTTPS connection
final chain =
Platform.script.resolve('certificates/server_chain.pem').toFilePath();
final key =
Platform.script.resolve('certificates/server_key.pem').toFilePath();
return SecurityContext()
..useCertificateChain(chain)
..usePrivateKey(key, password: 'dartdart');
}
startServer() async {
final ip = InternetAddress.anyIPv4;
// Configure a pipeline that logs requests.
final _handler = Pipeline().addMiddleware(logRequests()).addHandler(_router);
// For running in containers, we respect the PORT environment variable.
final port = int.parse(Platform.environment['PORT'] ?? '443');
final server =
await serve(_handler, ip, port, securityContext: getSecurityContext());
print('Server listening on port ${server.port}');
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Server Bind Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Server Bind'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
void initState() {
super.initState();
if (Platform.isAndroid) WebView.platform = AndroidWebView();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: WebView(
initialUrl:
'http://127.0.0.1:8888', //'http://${server.address.host}:${server.port}/index.html',
),
),
);
}
}
Here is the error I get:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: FileSystemException: Cannot open file, path = '/certificates/server_chain.pem' (OS Error: No such file or directory, errno = 2)
#0 _File.throwIfError (dart:io/file_impl.dart:635:7)
#1 _File.openSync (dart:io/file_impl.dart:479:5)
#2 _File.readAsBytesSync (dart:io/file_impl.dart:539:18)
#3 _SecurityContext.useCertificateChain (dart:io-patch/secure_socket_patch.dart:236:40)
#4 getSecurityContext (package:server_demo/main.dart:34:5)
#5 startServer (package:server_demo/main.dart:49:67)
#6 main (package:server_demo/main.dart:11:9)
#7 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#8 _rootRun (dart:async/zone.dart:1428:13)
#9 _CustomZone.run (dart:async/zone.dart:1328:19)
#10 _runZoned (dart:async/zone.dart:1863:10)
#11 runZonedGuarded (dart:async/zone.dart:1851:12)
#12 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:141:5)
#13 _delayEntrypointInv<…>
Assuming your certificate chain is located in assets/localhost.crt, the private key in assets/localhost.key and the assets folder listed under assets in your pubspec.yaml.
You can try with the following code:
void init() async {
var chain =
utf8.encode(await rootBundle.loadString('assets/localhost.crt'));
var key = utf8.encode(await rootBundle.loadString('assets/localhost.key'));
var context = SecurityContext()
..useCertificateChainBytes(chain)
..usePrivateKeyBytes(key);
var server =
await HttpServer.bindSecure(InternetAddress.anyIPv6, 443, context);
await server.forEach((HttpRequest request) {
request.response.statusCode = HttpStatus.ok;
request.response.write('Hello World!');
request.response.close();
});
}
The problem you are having is derived from how a dart script accesses other files vs how flutter packages and access files in the application bundle. Accessing them as assets in the bundle and passing them to the SecurityContext as Bytes did the trick for me.

Binding has not yet been initialized. When Using isloates

** I am creating google map location app
I tried to resolve my self but i am not able to fix this bug
Please help me to fix this bug
i am getting error when i create isolate for get location
I have used packages
google_maps_flutter: ^2.1.8
geocoding: ^2.0.4
geolocator: ^8.2.1
flutter_bloc: ^8.0.1
**
i got error
> Restarted application in 2,738ms.
D/MapsInitializer( 6872): preferredRenderer: null
D/zzca ( 6872): preferredRenderer: null
I/Google Maps Android API( 6872): Google Play services package version: 221215028
I/Google Maps Android API( 6872): Google Play services maps renderer version(legacy): 203115000
7
I/Counters( 6872): exceeded sample count in FrameTime
>
> I/m.example.g_ma( 6872): NativeAlloc concurrent copying GC freed 17476(988KB) AllocSpace objects, 0(0B) LOS objects, 50% free, 7MB/14MB, paused 172us total 133.433ms
10
I/Counters( 6872): exceeded sample count in FrameTime
I/m.example.g_ma( 6872): NativeAlloc concurrent copying GC freed 4201(193KB) AllocSpace objects, 0(0B) LOS objects, 49% free, 7MB/14MB, paused 138us total 149.308ms
7
I/Counters( 6872): exceeded sample count in FrameTime
I/chatty ( 6872): uid=10498(com.example.g_map) androidmapsapi- identical 1 line
3
I/Counters( 6872): exceeded sample count in FrameTime
E/flutter ( 6872): [ERROR:flutter/runtime/dart_isolate.cc(1098)] Unhandled exception:
E/flutter ( 6872): Binding has not yet been initialized.
E/flutter ( 6872): The "instance" getter on the ServicesBinding binding mixin is only available once that binding has been initialized.
E/flutter ( 6872): Typically, this is done by calling "WidgetsFlutterBinding.ensureInitialized()" or "runApp()" (the latter calls the former). Typically this call is done in the "void main()" method. The "ensureInitialized" method is idempotent; calling it multiple times is not harmful. After calling that method, the "instance" getter will return the binding.
E/flutter ( 6872): In a test, one can call "TestWidgetsFlutterBinding.ensureInitialized()" as the first line in the test's "main()" method to initialize the binding.
E/flutter ( 6872): If ServicesBinding is a custom binding mixin, there must also be a custom binding class, like WidgetsFlutterBinding, but that mixes in the selected binding, and that is the class that must be constructed before using the "instance" getter.
E/flutter ( 6872): #0 BindingBase.checkInstance.<anonymous closure>
package:flutter/…/foundation/binding.dart:281
E/flutter ( 6872): #1 BindingBase.checkInstance
package:flutter/…/foundation/binding.dart:363
E/flutter ( 6872): #2 ServicesBinding.instance
package:flutter/…/services/binding.dart:48
E/flutter ( 6872): #3 MethodChannel.binaryMessenger
package:flutter/…/services/platform_channel.dart:132
**My Code is **
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:g_map/cubit/googlemap_cubit.dart';
// import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'screens/home_page.dart';
void main() async{
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return BlocProvider<GooglemapCubit>(
create: (context) => GooglemapCubit(),
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Map'),
),
);
}
}
import 'dart:developer';
import 'package:geolocator/geolocator.dart';
class GLocationPermission{
Future<bool> checkPermission()async{
bool serviceEnabled ;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if(!serviceEnabled){
log("",error: "Location service is not enabled");
}
permission = await Geolocator.checkPermission();
if(permission == LocationPermission.denied){
permission = await Geolocator.requestPermission();
if(permission == LocationPermission.denied){
log("Permission is denied again ");
}
}
if(permission == LocationPermission.deniedForever){
log("",error: "Location permission denied forever");
return false;
}
if(permission == LocationPermission.whileInUse || permission == LocationPermission.always){
return true;
}else{
return false;
}
}
}
import 'dart:developer';
import 'dart:isolate';
import 'package:flutter/material.dart';
import 'package:flutter_bloc/flutter_bloc.dart';
import 'package:g_map/isolates/current_location_in_background.dart';
import 'package:g_map/services/location_permission.dart';
import 'package:geocoding/geocoding.dart';
// import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
// import 'package:geolocator/geolocator.dart';
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{
late GoogleMapController _mapController;
final TextEditingController _searchAddressController = TextEditingController();
final _locationPermission = GLocationPermission();
String searchedAddress = "";
late ReceivePort _receivePort;
late Isolate _isolate;
#override
void initState() {
_checkPermission();
super.initState();
}
Future<void> _checkPermission()async{
if(await _locationPermission.checkPermission() == true){
createIsloate();
}
}
Future<void> createIsloate()async{
_receivePort = ReceivePort();
_isolate = await Isolate.spawn(CurrentLocationInBackGround.getLocation, _receivePort.sendPort);
_receivePort.listen((message) {
log("message $message");
// final pos = message as Stream;
// pos.listen((event) {
// log("Event $event");
// });
},
onError: (error){
log("Error $error",error: error);
}
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Stack(
children: [
_googleMap(
inititalCameraPosition: const CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
)),
_searchAddressField(context: context)
],
));
}
Widget _googleMap({required CameraPosition inititalCameraPosition}) {
// buildWhen: (previous, current) => current.runtimeType == ,
return GoogleMap(
// minMaxZoomPreference: const MinMaxZoomPreference(1, 20),
zoomControlsEnabled: true,
onMapCreated: _onMapCreated,
myLocationButtonEnabled: true,
initialCameraPosition: inititalCameraPosition,
);
}
Widget _searchAddressField({required BuildContext context}){
return Card(
child: SizedBox(
width: double.infinity,
height: MediaQuery.of(context).size.height*.07,
child: Center(
child: TextField(
onChanged: (value){
// searchedAddress = context.read<GooglemapCubit>().searchAddress(address: value);
},
controller: _searchAddressController,
decoration: InputDecoration(border: InputBorder.none,
suffix: IconButton(onPressed:() => _searchAndNavigate(context: context), icon: const Icon(Icons.search))
),
),
),
),
);
}
Future<void> _searchAndNavigate({required BuildContext context})async{
final location = GeocodingPlatform.instance.locationFromAddress(_searchAddressController.text);
location.then((value){
debugPrint(value[0].latitude.toString());
debugPrint(value[0].longitude.toString());
_mapController.animateCamera(CameraUpdate.newCameraPosition(CameraPosition(
zoom: 12,
target:LatLng(value[0].latitude, value[0].longitude))));
});
}
void _onMapCreated(GoogleMapController controller) {
// _mapController = context.read<GooglemapCubit>().assignControllerOn(controller);
_mapController = controller;
}
}
import 'dart:developer';
import 'dart:isolate';
import 'package:geolocator/geolocator.dart';
class CurrentLocationInBackGround{
static void getLocation(SendPort sendPort)async{
final pos = await Geolocator.getCurrentPosition();
log("pos stream $pos");
sendPort.send(pos);
}
}
I think you tried to run geocoding methods on isolate because it's freezer the main thread
await placemarkFromCoordinates()
or
await locationFromAddress()
will freeze the main thread this bug on there repository
but here is a great solution
link to solution

GeoLocation package doesn't work in flutter while running on a real device

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:geolocator/geolocator.dart';
//import 'package:provider/provider.dart';
class Map extends StatefulWidget {
#override
State<StatefulWidget> createState() => _MapState();
}
class _MapState extends State<Map> {
Completer<GoogleMapController> _controllerGoogleMap = Completer();
GoogleMapController newGoogleMapController;
Position currentPosition;
var geoLocator = Geolocator();
void locatePosition() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.best);
currentPosition = position;
LatLng latLngPos = LatLng(position.latitude, position.longitude);
CameraPosition cameraPosition =
CameraPosition(target: latLngPos, zoom: 15.0);
newGoogleMapController
.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
}
static final CameraPosition _kGooglePlex = CameraPosition(
target: LatLng(37.42796133580664, -122.085749655962),
zoom: 14.4746,
);
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: GoogleMap(
mapType: MapType.normal,
myLocationButtonEnabled: true,
initialCameraPosition: _kGooglePlex,
myLocationEnabled: true,
zoomGesturesEnabled: true,
zoomControlsEnabled: true,
onMapCreated: (GoogleMapController controller) {
_controllerGoogleMap.complete(controller);
newGoogleMapController = controller;
locatePosition();
},
),
),
);
}
}
Under the debug terminal
Launching lib\main.dart on vivo 1906 in debug mode...
lib\main.dart:1 √ Built build\app\outputs\flutter-apk\app-debug.apk. I/flutter ( 9154):
Observatory listening on ************************************ I/flutter ( 9613):
Observatory listening on ************************************ E/flutter ( 9613): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception:
User denied permissions to access the device's location. E/flutter ( 9613):
#0 MethodChannelGeolocator._handlePlatformException package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:199
E/flutter ( 9613): #1 MethodChannelGeolocator.getCurrentPosition package:geolocator_platform_interface/…/implementations/method_channel_geolocator.dart:
118 E/flutter ( 9613): <asynchronous suspension> E/flutter ( 9613): #2 _MapState.locatePosition package:donation_yoga/screens/maps.dart:
21 E/flutter ( 9613): <asynchronous suspension> E/flutter ( 9613):
I never denied permission my permission is on,
Also the map don't show the my location button even though I have enabled it to get current location,
just shows zoom in and out button and the map that's it.
Using Flutter 2.2.1
google_maps_flutter: ^2.0.6
geolocator: ^7.0.3
PS: I have tried location package but it throws a lot of errors such as location_web not found etc,
For All Users Getting "Unhandled Exception: User denied permissions to access the device's location"
pubspec.yaml
Add geolocator: ^8.0.1 under dependencies:
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
geolocator: ^8.0.1
AndroidManifest.xml
You will see the following :
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.get_weather">
Add the following under the above code:
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.hardware.location.gps" />
main.dart
import 'package:flutter/material.dart';
import 'package:get_weather/screens/loading_screen.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: LoadingScreen(),
);
}
}
loading_screen.dart
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
class LoadingScreen extends StatefulWidget {
#override
_LoadingScreenState createState() => _LoadingScreenState();
}
class _LoadingScreenState extends State<LoadingScreen> {
void getLocation() async {
bool serviceEnabled;
LocationPermission permission;
// Test if location services are enabled.
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
// Location services are not enabled don't continue
// accessing the position and request users of the
// App to enable the location services.
return Future.error('Location services are disabled.');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
// Permissions are denied, next time you could try
// requesting permissions again (this is also where
// Android's shouldShowRequestPermissionRationale
// returned true. According to Android guidelines
// your App should show an explanatory UI now.
return Future.error('Location permissions are denied');
}
}
if (permission == LocationPermission.deniedForever) {
// Permissions are denied forever, handle appropriately.
return Future.error(
'Location permissions are permanently denied, we cannot request permissions.');
}
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
print(position);
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: ElevatedButton(
onPressed: () {
//Get the current location
getLocation();
},
child: Text('Get Location'),
),
),
);
}
}
The code in loading_screen.dart will help you get the 'User denied permission' resolved.
try adding the forceLocationManager clause to your function:
void locatePosition() async {
Position position = await Geolocator.getLastKnownPosition({ bool forceAndroidLocationManager = true}
);
currentPosition = position;
LatLng latLngPos = LatLng(position.latitude, position.longitude);
CameraPosition cameraPosition =
CameraPosition(target: latLngPos, zoom: 15.0);
newGoogleMapController
.animateCamera(CameraUpdate.newCameraPosition(cameraPosition));
}
also check your android manifest for location:
<manifest ... >
<!-- To request foreground location access, declare one of these
permissions. -->
<uses-permission
android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"
/>
</manifest>
also keep your desired accuracy low ,accuracy at best creates privacy chaos with the device ,so it requires additional steps

GoogleMap in PageView

I have a googlemap located on containers in a pageview... When u swipe between the pages that contain these googlemap widgets, the pagesnapping breaks... so inside my code when I do
class Homepage extends StatelessWidget {
#override build(BuildContext context){
return PageView(
children: <Widget>[
Container(color:Colors.red),
Container(color:Colors.green),
Container(color:Colors.blue),
Container(color:Colors.yellow),
Container(color:Colors.pink),
// Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
// Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
// Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
// Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),))
],
);
}
This, it works fine and all the pages snap perfectly.. However when I uncomment the GoogleMap widgets like so:
class Homepage extends StatelessWidget {
#override build(BuildContext context){
return PageView(
children: <Widget>[
// Container(color:Colors.red),
// Container(color:Colors.green),
// Container(color:Colors.blue),
// Container(color:Colors.yellow),
// Container(color:Colors.pink),
Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)),
Container(child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),))
],
);
}
}
The PageView works for a while but breaks (on IOS) and this error is (sometimes) shown in the console:
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: 'package:flutter/src/gestures/converter.dart': Failed assertion: line 155 pos 18: '!state.down': is not true.
#0 _AssertionError._doThrowNew (dart:core/runtime/liberrors_patch.dart:40:39)
#1 _AssertionError._throwNew (dart:core/runtime/liberrors_patch.dart:36:5)
#2 PointerEventConverter.expand (package:flutter/src/gestures/converter.dart:155:18)
#3 _SyncIterator.moveNext (dart:core/runtime/libcore_patch.dart:152:12)
#4 ListQueue.addAll (dart:collection/queue.dart:715:25)
#5 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:83:27)
#6 _rootRunUnary (dart:async/zone.dart:1136:13)
#7 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#8 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#9 _invoke1 (dart:ui/hooks.dart:223:10)
#10 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5
Anyone seen and fixed this?
Thanks for your attention..
John.
I had a similar issue working with google map in pageview but after searching online I got a solution that finally worked
All I did was put the google map in a stateful widget, used the with AutomaticKeepAliveClientMixin and #override bool get wantKeepAlive => true; and called in the required widget
This is the stateful widget containing the google map
class GoogleMapWidget extends StatefulWidget{
const GoogleMapWidget({Key? key}) : super(key: key);
#override
_GoogleMapWidgetState createState() => _GoogleMapWidgetState();
}
class _GoogleMapWidgetState extends State<GoogleMapWidget> with AutomaticKeepAliveClientMixin {
#override
bool get wantKeepAlive => true;
#override
Widget build(BuildContext context) {
return Container(
child:GoogleMap(initialCameraPosition: CameraPosition(target:LatLng(0, 0)),)
);
}
}
Then you can call it from your Homepage like so
class Homepage extends StatelessWidget {
#override
build(BuildContext context){
return PageView(
children: <Widget>[
GoogleMapWidget(),
GoogleMapWidget(),
],
);
}
}
I hope this is the answer you're looking for
don't use Pageview instead use PageView.builder and then create a global list
List latLong = [
// pass all google maps and latLong values here
];
then on itemBuilder pass the latlong according to index and don't forget to turn gestureDetector on your googleMaps else it'll also scroll the map