LateInitializationError: Field 'initialPosition' has not been initialized - flutter

I am trying to create map screen but I found the below error:
======== Exception caught by widgets library =======================================================
The following LateError was thrown building Consumer<MapViewModel>(dirty, dependencies: [_InheritedProviderScope<MapViewModel>]):
LateInitializationError: Field 'initialPosition' has not been initialized.
The relevant error-causing widget was:
Consumer<MapViewModel> file:///Users/mahmoudalharoon/Desktop/Air%20Forces/aireforces/lib/screens/BaseScreen.dart:44:14
When the exception was thrown, this was the stack:
#0 MapViewModel.initialPosition (package:airforces/screens/map/viewmodel/map_viewmodel.dart)
#1 MapScreen.build.<anonymous closure> (package:airforces/screens/map/view/map_screen.dart:19:27)
#2 Consumer.buildWithChild (package:provider/src/consumer.dart:180:19)
#3 SingleChildStatelessWidget.build (package:nested/nested.dart:259:41)
#4 StatelessElement.build (package:flutter/src/widgets/framework.dart:4648:28)
...
====================================================================================================
and this is the below ViewModel I have:
import 'package:airforces/enums/ScreenState.dart';
import 'package:airforces/screens/BaseViewModel.dart';
import 'package:geocoding/geocoding.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapViewModel extends BaseViewModel {
late LatLng? initialPosition;
late LatLng lastMapPosition = initialPosition!;
void getUserLocation() async {
Position position = await Geolocator.getCurrentPosition(
desiredAccuracy: LocationAccuracy.high);
List<Placemark> placemarks = await placemarkFromCoordinates(
position.latitude, position.longitude);
initialPosition = LatLng(position.latitude, position.longitude);
print('${placemarks[0].name}');
setState(ViewState.Idle);
}
}
and this is the below map screen I have:
import 'package:airforces/screens/BaseScreen.dart';
import 'package:airforces/screens/map/viewmodel/map_viewmodel.dart';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
class MapScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return BaseScreen<MapViewModel>(
onFinish: (_) {
},
onModelReady: (mapViewModel) {
mapViewModel.getUserLocation();
},
builder: (context, mapViewModel, child){
return GoogleMap(
initialCameraPosition: CameraPosition(
target: mapViewModel.initialPosition!,
),
myLocationEnabled: true,
);
},
);
}
}

The issue is occurring because initialPosition is null until the late initialization occurs, but it is being converted to a non-nullable type before the late initialization occurs here: mapViewModel.initialPosition!.
You can resolve this one of two ways.
Return a default position if initialPosition is null when accessing it.
target: mapViewModel.initialPosition ?? [defaultPosition];
Display a loading widget until initialPosition is initialized, then display GoogleMap.
Both of these solutions will require a minor state management solution in order to update the widget when initialPosition is finally initialized.

Related

Flutter: Video player not initialized

I have a video preview widget that takes either a string url or a video file. If the parameter is a String, it downloads the file from online/the cache. With this is mind, my implementation is as follows:
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:hero/helpers/cache_manager/cache_manager.dart';
import 'package:video_player/video_player.dart';
import 'package:chewie/chewie.dart';
class WaveVideoPreview extends StatefulWidget {
final File? videoFile;
final String? videoUrl;
WaveVideoPreview({this.videoFile, this.videoUrl});
#override
_WaveVideoPreviewState createState() => _WaveVideoPreviewState();
}
class _WaveVideoPreviewState extends State<WaveVideoPreview> {
late VideoPlayerController? _controller;
late ChewieController _chewieController;
void initState() {
super.initState();
_initAsync();
}
void _initAsync() async {
File? _videoFile = widget.videoFile;
if (_videoFile == null) {
_videoFile = await getVideo(_videoFile);
}
_controller = VideoPlayerController.file(_videoFile!)
..initialize().then((_) {
setState(() {
_chewieController = ChewieController(
videoPlayerController: _controller!,
aspectRatio: _controller!.value.aspectRatio,
autoPlay: false,
looping: true,
allowFullScreen: false,
);
});
});
}
Future<File?> getVideo(File? _videoFile) async {
_videoFile = await MyCache.getVideo(widget.videoUrl!);
return _videoFile;
}
#override
Widget build(BuildContext context) {
return Container(
height: 200.0,
child: (_controller?.value.isInitialized ?? false)
? Chewie(
controller: _chewieController,
)
: SizedBox.shrink(),
);
}
#override
void dispose() {
_controller!.dispose();
_chewieController.dispose();
super.dispose();
}
}
with
static Future<File?> getVideo(String url) async {
DefaultCacheManager _cacheManager = DefaultCacheManager();
File? file = await _cacheManager.getSingleFile(url);
return file;
}
Which is throwing the error:
════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building WaveVideoPreview(dirty, state: _WaveVideoPreviewState#659ef):
LateInitializationError: Field '_controller#1875314998' has not been initialized.
The relevant error-causing widget was
WaveVideoPreview
lib/…/widget/wave_tile.dart:84
When the exception was thrown, this was the stack
#0 _WaveVideoPreviewState._controller (package:hero/screens/home/home_screens/views/waves/widget/video/wave_video_preview.dart)
package:hero/…/video/wave_video_preview.dart:1
#1 _WaveVideoPreviewState.build
package:hero/…/video/wave_video_preview.dart:57
Anyone know whats going on? I've tried changing the video player between nullable and non nullable, but still to no avail. Also as you can see i have a null check, but still nothing.
_initAsync is using async and it will take some frame to initialize the controllers.
It would be better to use FutureBuilder for this. or make those nullable and the do a null check while using it.
VideoPlayerController? _controller;
ChewieController? _chewieController;

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

The getter 'length' was called on null. fetch from api

I am trying to fetch data from api its splash screen of my app I want user wait 5 second when app is launched and then go to next screen but when I tried fetch data from api I received The getter 'length' was called on null. please help me here is my code I tried resolve it number of other resources but failed to find solution that's why I am posting my question is here please check and help
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_app/main.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(new MaterialApp(
home: new SplashScreen(),
debugShowCheckedModeBanner: false,
routes: <String, WidgetBuilder>{
'/MyHomePage': (BuildContext context) => new MyHomePage()
},
));
}
class SplashScreen extends StatefulWidget {
#override
_SplashScreenState createState() => new _SplashScreenState();
}
class _SplashScreenState extends State<SplashScreen> {
startTime() async {
var _duration = new Duration(seconds: 5);
return new Timer(_duration, navigationPage);
}
void navigationPage() {
Navigator.of(context).pushReplacementNamed('/MyHomePage');
}
bool _loading=true;
Map data;
List userData=null;
Future getData() async {
http.Response response = await http.get("https://livinghopemobile.com/public/api/fetch-site-settings?token=123ab_#_#AbCD");
data = json.decode(response.body);
debugPrint(response.body);
setState(() {
userData = data["data"];
_loading=false;
// print(userData[0]['title']);
});
}
#override
void initState() {
super.initState();
//startTime();
getData();
}
#override
Widget build(BuildContext context) {
return new Scaffold(
body: ListView.builder(
itemCount:userData.length,
itemBuilder: (context, index) {
return Container(
child: Image.network(userData[index]['site_logo']),
);
}
)
);
}
}
Launching lib/ui/SplashScreen.dart on iPhone 11 Pro Max in debug mode...
Running Xcode build...
Xcode build done. 23.8s
Debug service listening on ws://127.0.0.1:60469/bL7bmRYyhoc=/ws
Syncing files to device iPhone 11 Pro Max...
════════ Exception caught by widgets library ═══════════════════════════════════════════════════════
The following NoSuchMethodError was thrown building SplashScreen(dirty, state: _SplashScreenState#5fa75):
The getter 'length' was called on null.
Receiver: null
Tried calling: length
The relevant error-causing widget was:
SplashScreen file:///Users/apple/livinghopev4/livinghope4ios/lib/ui/SplashScreen.dart:10:15
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _SplashScreenState.build (package:flutter_app/ui/SplashScreen.dart:61:30)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4612:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4495:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4667:11)
...
════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: {"status":200,"message":"Data fetched successfully","data":{"id":1,"site_logo":"https:\/\/livinghopemobile.com\/public\/storage\/site_logo\/270421_122025_image.png","site_name":"Living hope","created_at":null,"updated_at":"2021-04-27T07:20:26.000000Z"}}
[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'List<dynamic>'
#0 _SplashScreenState.getData.<anonymous closure> (package:flutter_app/ui/SplashScreen.dart:41:7)
#1 State.setState (package:flutter/src/widgets/framework.dart:1267:30)
#2 _SplashScreenState.getData (package:flutter_app/ui/SplashScreen.dart:40:5)
<asynchronous suspension>
This is because data is not type List, and userData is null hence there is no length to it when you are calling userData.length in ListView.builder.
Change null to [].
{"status":200,"message":"Data fetched successfully","data":{"id":1,"site_logo":"https:\/\/livinghopemobile.com\/public\/storage\/site_logo\/270421_122025_image.png","site_name":"Living hope","created_at":null,"updated_at":"2021-04-27T07:20:26.000000Z"}}
You could append the received data to userData, like: userData.add(data).
You try it:
itemCount:userData.length == null ? 0 : userData.length
Data is returning in Object and you are taking it as List. This is the reason you are getting the error.
Solution:
Don't use Listview.builder as api response is just an object(Map<String, dynamic>).
You can simply use
Image.network(userData['site_logo']),
and everthing will be fine.

Flutter Exception : The getter 'latitude' was called on null. Receiver: null Tried calling: latitude

This is the code that i have written to get current location and add some markers
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:geolocator/geolocator.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
class Map extends StatefulWidget {
#override
_NewMapState createState() => _NewMapState();
}
Future setMapStyle(GoogleMapController controller, BuildContext context) async {
String value = await DefaultAssetBundle.of(context)
.loadString('assets/maps/map_style.json');
await controller.setMapStyle(value);
}
class _NewMapState extends State<Map> {
GoogleMapController _controller;
Position position;
Widget _child;
Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
BitmapDescriptor pinLocationIcon;
#override
void initState() {
_child = SpinKitRipple(
itemBuilder: (BuildContext context, int index) {
return DecoratedBox(
decoration: BoxDecoration(
color: index.isEven ? Colors.grey : Color(0xffffb838),
),
);
},
);
getCurrentLocation();
populateClients();
setCustomMapPin();
super.initState();
}
void getCurrentLocation() async {
Position res = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high);
setState(() {
position = res;
_child = mapWidget();
});
}
populateClients() async {
FirebaseFirestore.instance.collection('points').get().then((docs) {
if (docs.docs.isNotEmpty) {
for (int i = 0; i < docs.docs.length; ++i) {
initMarker(docs.docs[i].data(), docs.docs[i].id);
}
}
});
}
void initMarker(tomb, tombId) {
var markerIdVal = tombId;
final MarkerId markerId = MarkerId(markerIdVal);
final Marker marker = Marker(
markerId: markerId,
position: LatLng(tomb['location'].latitude, tomb['location'].longitude),
icon: pinLocationIcon,
infoWindow: InfoWindow(title: 'Shop', snippet: tombId),
onTap: () {
_settingModalBottomSheet(context,markerIdVal);
},
);
setState(() {
markers[markerId] = marker;
});
}
........ here is adding markers and map
The code gives the desired output but the console prints and exception called
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude
What could be the issue i have tried a lot but could not find any valid reason for it
full error
Exception caught by widgets library ═══════════════════════════════════
The following NoSuchMethodError was thrown building Map(dirty, state: _NewMapState#22070):
The getter 'latitude' was called on null.
Receiver: null
Tried calling: latitude
The relevant error-causing widget was
Map
lib\Pages\home.dart:46
When the exception was thrown, this was the stack
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
#1 _NewMapState.mapWidget
package:map/Pages/test.dart:106
#2 _NewMapState.build
package:map/Pages/test.dart:97
#3 StatefulElement.build
package:flutter/…/widgets/framework.dart:4744
#4 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4627
...
It means your tomb['location'] == null.
Check your code, find out why tomb['location'] is null.

Unimplemented handling of missing static target, Flutter

I'm writing my Flutter code but I keep getting the error of Unimplemented handling of missing the static target. there is no other error give so I don't know why I'm getting this and there is no way for me to debug it.
The error I'm getting is:
══════ Exception caught by widgets library ═══════════════════════════════════
The following _CompileTimeError was thrown building Wrapper(dirty, dependencies: [InheritedProvider<User>], state: _Wrapper#576d6):
Unimplemented handling of missing static target
The relevant error-causing widget was
Wrapper
lib\main.dart:28
When the exception was thrown, this was the stack
#0 StatefulElement.build
package:flutter/…/widgets/framework.dart:4334
#1 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4223
#2 Element.rebuild
package:flutter/…/widgets/framework.dart:3947
#3 StatefulElement.update
package:flutter/…/widgets/framework.dart:4413
#4 Element.updateChild
package:flutter/…/widgets/framework.dart:2977
...
════════════════════════════════════════════════════════════════════════════════
Reloaded 5 of 544 libraries in 350ms.
════════ Exception caught by widgets library ═══════════════════════════════════
Unimplemented handling of missing static target
The relevant error-causing widget was
Wrapper
My code is :
import 'package:sociagrowapp/models/user.dart';
import 'package:sociagrowapp/HomePages/Home.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:sociagrowapp/Authenticate/authenticate.dart';
//import 'package:package_info/package_info.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'package:sociagrowapp/services/firestore.dart';
import 'package:http/http.dart' as http;
class Wrapper extends StatefulWidget {
#override
createState() => _Wrapper();
}
class _Wrapper extends State<Wrapper> {
#override
Widget build(BuildContext context) {
Future getversionnumber() async {
var data = http.get('https://sociagrow.com/version.html');
print(data);
return data;
}
return FutureBuilder(
future: getversionnumber(),
builder: (BuildContext context, snapshot) {
if (snapshot.hasData) {
final user = Provider.of<User>(context);
print(user);
var version = snapshot.data;
// return either the Home or Authenticate widget
if (version == false) {
return Text('Oh no You need to update');
} else {
if (user == null) {
print('Should Changed 3');
return Scaffold(body: Authenticate());
} else {
return PageData();
}
}
} else {
return SpinKitThreeBounce(
color: Colors.blue,
);
}
});
}
}
The strange part is that when I debug it in visual studio code it runs but when I resave and hot reload it I get this error. The problem is not in the http.get() because I got the error with other future functions and firestore as well. really strange though I haven't encountered this type of error and I can't find anything about this error in the internet that could be helpful.
May be hot-reload cache lead to this problem, I just encounter the same problem and I fixed it by stop project then restart it.
You can solve this problem by stopping the debugging or terminate the app.
Then, try to restart or debug the app.