App crashed while trying to initialize StreamSubscription - dart

I want to track distance of user continuously using StreamSubscription but every time the app crashed. Plugin used for locating user is location. here is the code.
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:flutter/material.dart';
import 'dart:async';
import 'package:location/location.dart';
import 'package:latlong/latlong.dart' as LatLong;
const LatLng defaultPosition = LatLng(0.906706, 123.259054);
class MapRoute extends StatefulWidget {
final LatLng lokasiKegiatan;
final double maxPerimeter;
MapRoute(this.lokasiKegiatan, this.maxPerimeter);
#override
_MapRouteState createState() => _MapRouteState();
}
class _MapRouteState extends State<MapRoute> {
Completer<GoogleMapController> mapController = Completer();
bool isLoading = false;
bool isUserNearby = false;
bool isUserVisible = true;
Location _locationManager = new Location();
StreamSubscription<LocationData> _locationTrackerSub;
LocationData _lokasiTerkini;
String errorMessage;
double distanceToLocation;
#override
void initState() {
// TODO: implement initState
super.initState();
_locationTrackerSub = _locationManager.onLocationChanged().listen((data) {
setState(() {
_lokasiTerkini = data;
});
});
}
#override
void dispose() {
// TODO: implement dispose
_locationTrackerSub = null;
super.dispose();
}
#override
Widget build(BuildContext context) {
MarkerId markerId = MarkerId('ACARA PEMDA');
Marker markerLokasi = new Marker(
markerId: markerId,
position: widget.lokasiKegiatan,
infoWindow: InfoWindow(
title: 'Apel Bersama',
snippet: 'Apel Bersama PEMDA BOLMUT',
),
icon: BitmapDescriptor.defaultMarkerWithHue(BitmapDescriptor.hueRed));
final Map<MarkerId, Marker> markers = <MarkerId, Marker>{};
markers[markerId] = markerLokasi;
return Column(
mainAxisSize: MainAxisSize.max,
children: <Widget>[
Padding(
padding: EdgeInsets.all(3.0),
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(30.0)),
child: Column(
children: <Widget>[
SizedBox(
height: 400,
child: Stack(
children: <Widget>[
GoogleMap(
mapType: MapType.normal,
onMapCreated: _onMapCreated,
myLocationEnabled: isUserVisible,
initialCameraPosition: CameraPosition(
target: defaultPosition,
zoom: 15,
),
markers: Set<Marker>.of(markers.values),
),
Positioned(
top: 12,
left: 12,
child: SizedBox(
width: 39,
height: 37,
child: RaisedButton(
elevation: 1.0,
padding: EdgeInsets.all(2.0),
shape: RoundedRectangleBorder(
side: BorderSide(
width: 0.5,
color: Colors.white,
),
borderRadius: BorderRadius.all(
Radius.circular(5.0),
),
),
child: Icon(
Icons.location_on,
color: Colors.black54,
size: 27,
),
color: Colors.white,
onPressed: _goToLokasiKegiatan,
),
),
),
Positioned(
top: 25,
left: 57,
child: distanceToLocation != null
? Text('0 KM')
: Text(
'menghitung jarak ke lokasi kegiatan...',
style: ThemeData().textTheme.title,
),
)
],
),
),
],
),
),
),
SizedBox(
height: 20.0,
),
RaisedButton(
color: Colors.blue,
shape:
CircleBorder(side: BorderSide(width: 1.0, color: Colors.amber)),
elevation: 5,
child: Icon(
Icons.fingerprint,
color: Colors.white,
size: 74,
),
onPressed: isUserNearby ? () {} : null)
],
);
}
void _onMapCreated(GoogleMapController controller) async {
mapController.complete(controller);
_goToLokasiKegiatan();
}
void _goToLokasiKegiatan() async {
mapController.future.then((controller) {
controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(target: widget.lokasiKegiatan, zoom: 18.0),
),
);
});
}
double calculateUserDistance(LocationData currentPosition) {
//converting from gmap to latlong package
var lat = widget.lokasiKegiatan.latitude;
var long = widget.lokasiKegiatan.longitude;
var ulat = currentPosition.latitude;
var ulong = currentPosition.longitude;
var jarak = LatLong.Distance();
double meter = jarak.as(
LatLong.LengthUnit.Meter,
new LatLong.LatLng(lat, long),
new LatLong.LatLng(ulat, ulong),
);
return meter;
}
void _processUserLocation(LocationData locationData) async {
var distanceToLocation = calculateUserDistance(locationData);
if (distanceToLocation <= widget.maxPerimeter) {
setState(() {
isUserNearby = true;
});
}
setState(() {
this.distanceToLocation = distanceToLocation;
});
}
void _initLocation() async {
LocationData location;
try {
if (await _locationManager.hasPermission()) {
_locationTrackerSub = _locationManager.onLocationChanged().listen(
(locationData) {
setState(() {
_lokasiTerkini = locationData;
});
},
);
}
} catch (e) {
debugPrint(e);
}
}
}
and the debug output..
Launching lib\main.dart on ASUS X00QD in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/SimplePermission(16555): Checking permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
Reloaded 2 of 449 libraries in 1,234ms.
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
Reloaded 2 of 449 libraries in 951ms.
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 2
I/SimplePermission(16555): Requesting permission : android.permission.ACCESS_FINE_LOCATION
I/SimplePermission(16555): Requesting permission status : 3
I/zzbz (16555): Making Creator dynamically
W/mple.absensigp(16555): Unsupported class loader
W/mple.absensigp(16555): Skipping duplicate class check due to unsupported classloader
I/DynamiteModule(16555): Considering local module com.google.android.gms.maps_dynamite:0 and remote module com.google.android.gms.maps_dynamite:221
I/DynamiteModule(16555): Selected remote version of com.google.android.gms.maps_dynamite, version >= 221
V/DynamiteModule(16555): Dynamite loader version >= 2, using loadModule2NoCrashUtils
W/mple.absensigp(16555): Unsupported class loader
W/mple.absensigp(16555): Skipping duplicate class check due to unsupported classloader
I/Google Maps Android API(16555): Google Play services client version: 12451000
I/Google Maps Android API(16555): Google Play services package version: 15090039
W/mple.absensigp(16555): Accessing hidden field Ljava/nio/Buffer;->address:J (light greylist, reflection)
D/NetworkSecurityConfig(16555): No Network Security Config specified, using platform default
I/DpmTcmClient(16555): RegisterTcmMonitor from: com.android.okhttp.TcmIdleTimerMonitor
W/DynamiteModule(16555): Local module descriptor class for com.google.android.gms.googlecertificates not found.
I/DynamiteModule(16555): Considering local module com.google.android.gms.googlecertificates:0 and remote module com.google.android.gms.googlecertificates:4
I/DynamiteModule(16555): Selected remote version of com.google.android.gms.googlecertificates, version >= 4
W/mple.absensigp(16555): Unsupported class loader
W/mple.absensigp(16555): Skipping duplicate class check due to unsupported classloader
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
W/OpenGLRenderer(16555): swapBuffers encountered EGL error 12301 on 0x75f6b20a00, halting rendering...
I/Google Maps Android API(16555): Google Play services package version: 15090039
W/System (16555): A resource failed to call release.
I/Google Maps Android API(16555): Google Play services package version: 15090039
I/Google Maps Android API(16555): Google Play services package version: 15090039
W/System (16555): A resource failed to call release.
W/System (16555): A resource failed to call release.
I/Google Maps Android API(16555): Google Play services package version: 15090039
W/System (16555): A resource failed to call release.
I/Google Maps Android API(16555): Google Play services package version: 15090039
I/mple.absensigp(16555): Compiler allocated 4MB to compile void android.widget.TextView.<init>(android.content.Context, android.util.AttributeSet, int, int)
W/System (16555): A resource failed to call release.
Reloaded 3 of 449 libraries in 1,114ms.
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
I/Adreno (16555): DequeueBuffer: dequeueBuffer failed
W/OpenGLRenderer(16555): swapBuffers encountered EGL error 12301 on 0x75ef08a900, halting rendering...
E/flutter (16555): [ERROR:flutter/shell/platform/android/platform_view_android_jni.cc(40)] java.lang.NoClassDefFoundError: Failed resolution of: Landroidx/core/app/ActivityCompat;
E/flutter (16555): at com.lyokone.location.LocationPlugin.checkPermissions(LocationPlugin.java:186)
E/flutter (16555): at com.lyokone.location.LocationPlugin.onListen(LocationPlugin.java:271)
E/flutter (16555): at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onListen(EventChannel.java:181)
E/flutter (16555): at io.flutter.plugin.common.EventChannel$IncomingStreamRequestHandler.onMessage(EventChannel.java:160)
E/flutter (16555): at io.flutter.view.FlutterNativeView$PlatformMessageHandlerImpl.handleMessageFromDart(FlutterNativeView.java:188)
E/flutter (16555): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:202)
E/flutter (16555): at android.os.MessageQueue.nativePollOnce(Native Method)
E/flutter (16555): at android.os.MessageQueue.next(MessageQueue.java:326)
E/flutter (16555): at android.os.Looper.loop(Looper.java:163)
E/flutter (16555): at android.app.ActivityThread.main(ActivityThread.java:6732)
E/flutter (16555): at java.lang.reflect.Method.invoke(Native Method)
E/flutter (16555): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
E/flutter (16555): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
E/flutter (16555): Caused by: java.lang.ClassNotFoundException: Didn't find class "androidx.core.app.ActivityCompat" on path: DexPathList[[zip file "/system/framework/org.apache.http.legacy.boot.jar", zip file "/data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/base.apk"],nativeLibraryDirectories=[/data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64, /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/base.apk!/lib/arm64-v8a, /system/lib64]]
E/flutter (16555): at dalvik.system.BaseDexClassLoader.findClass(BaseDexClassLoader.java:134)
E/flutter (16555): at java.lang.ClassLoader.loadClass(ClassLoader.java:379)
E/flutter (16555): at java.lang.ClassLoader.loadClass(ClassLoader.java:312)
E/flutter (16555): ... 13 more
E/flutter (16555):
F/flutter (16555): [FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(77)] Check failed: CheckException(env).
F/libc (16555): Fatal signal 6 (SIGABRT), code -6 (SI_TKILL) in tid 16555 (mple.absensigps), pid 16555 (mple.absensigps)
*** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
Build fingerprint: 'asus/WW_X00QD/ASUS_X00QD:9/PPR1.180610.009/16.0611.1901.1-0:user/release-keys'
Revision: '0'
ABI: 'arm64'
pid: 16555, tid: 16555, name: mple.absensigps >>> com.example.absensigps <<<
signal 6 (SIGABRT), code -6 (SI_TKILL), fault addr --------
Abort message: '[FATAL:flutter/shell/platform/android/platform_view_android_jni.cc(77)] Check failed: CheckException(env).
'
x0 0000000000000000 x1 00000000000040ab x2 0000000000000006 x3 0000000000000008
x4 0000000000000000 x5 0000000000000000 x6 0000000000000000 x7 0000008000000000
x8 0000000000000083 x9 afcf0ea64e096394 x10 0000000000000000 x11 fffffffc7ffffbdf
x12 0000000000000001 x13 0000000000000018 x14 ffffffffffffffff x15 0000f282b913c801
x16 00000076978b02c8 x17 00000076977ee0d0 x18 0000000000000001 x19 00000000000040ab
x20 00000000000040ab x21 0000007fd63435b8 x22 00000000000000c3 x23 0000000000000099
x24 00000075f8bbdfc0 x25 0000000000000050 x26 00000075eb83a6a0 x27 0000007612cf7c88
x28 0000000000000034 x29 0000007fd63435a0
sp 0000007fd6343560 lr 00000076977e2bfc pc 00000076977e2c24
backtrace:
#00 pc 0000000000021c24 /system/lib64/libc.so (abort+116)
#01 pc 00000000006b7e48 /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#02 pc 00000000006aca1c /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#03 pc 00000000006abc74 /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#04 pc 00000000006e5018 /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#05 pc 00000000006b9368 /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#06 pc 00000000006baf58 /data/app/com.example.absensigps-vaz4urV31quLBNjs6K8-IA==/lib/arm64/libflutter.so (offset 0x690000)
#07 pc 00000000000141c0 /system/lib64/libutils.so (android::Looper::pollInner(int)+856)
#08 pc 0000000000013dcc /system/lib64/libutils.so (android::Looper::pollOnce(int, int*, int*, void**)+60)
#09 pc 0000000000120a94 /system/lib64/libandroid_runtime.so (android::android_os_MessageQueue_nativePollOnce(_JNIEnv*, _jobject*, long, int)+44)
#10 pc 00000000003e4fec /system/framework/arm64/boot-framework.oat (offset 0x3d0000) (android.media.MediaExtractor.seekTo [DEDUPED]+140)
#11 pc 000000000000284c /dev/ashmem/dalvik-jit-code-cache (deleted) (android.os.MessageQueue.next+204)
#12 pc 000000000006c8d4 /dev/ashmem/dalvik-jit-code-cache (deleted) (android.os.Looper.loop+404)
#13 pc 0000000000554cdc /system/lib64/libart.so (art_quick_osr_stub+44)
#14 pc 0000000000306f9c /system/lib64/libart.so (art::jit::Jit::MaybeDoOnStackReplacement(art::Thread*, art::ArtMethod*, unsigned int, int, art::JValue*)+1996)
#15 pc 000000000052ad1c /system/lib64/libart.so (MterpMaybeDoOnStackReplacement+144)
#16 pc 000000000054b9f0 /system/lib64/libart.so (ExecuteMterpImpl+33136)
#17 pc 0000000000b15512 /system/framework/boot-framework.vdex (android.os.Looper.loop+986)
#18 pc 0000000000252fc0 /system/lib64/libart.so (_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_6JValueEb.llvm.3783761849+488)
#19 pc 0000000000258ab4 /system/lib64/libart.so (art::interpreter::ArtInterpreterToInterpreterBridge(art::Thread*, art::CodeItemDataAccessor const&, art::ShadowFrame*, art::JValue*)+216)
#20 pc 00000000002792a0 /system/lib64/libart.so (bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*)+940)
#21 pc 0000000000525c14 /system/lib64/libart.so (MterpInvokeStatic+204)
#22 pc 0000000000547194 /system/lib64/libart.so (ExecuteMterpImpl+14612)
#23 pc 00000000003919ec /system/framework/boot-framework.vdex (android.app.ActivityThread.main+256)
#24 pc 0000000000252fc0 /system/lib64/libart.so (_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_6JValueEb.llvm.3783761849+488)
#25 pc 0000000000514fa4 /system/lib64/libart.so (artQuickToInterpreterBridge+1020)
#26 pc 000000000055dafc /system/lib64/libart.so (art_quick_to_interpreter_bridge+92)
#27 pc 0000000000554c4c /system/lib64/libart.so (art_quick_invoke_static_stub+604)
#28 pc 00000000000cf6e8 /system/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+232)
#29 pc 000000000045c840 /system/lib64/libart.so (art::(anonymous namespace)::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::(anonymous namespace)::ArgArray*, art::JValue*, char const*)+104)
#30 pc 000000000045e294 /system/lib64/libart.so (art::InvokeMethod(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jobject*, _jobject*, unsigned long)+1440)
#31 pc 00000000003ee1d4 /system/lib64/libart.so (art::Method_invoke(_JNIEnv*, _jobject*, _jobject*, _jobjectArray*)+52)
#32 pc 000000000011e6d4 /system/framework/arm64/boot-core-oj.oat (offset 0x114000) (java.lang.Class.getDeclaredMethodInternal [DEDUPED]+180)
#33 pc 0000000000554988 /system/lib64/libart.so (art_quick_invoke_stub+584)
#34 pc 00000000000cf6c8 /system/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+200)
#35 pc 000000000027f2b4 /system/lib64/libart.so (art::interpreter::ArtInterpreterToCompiledCodeBridge(art::Thread*, art::ArtMethod*, art::ShadowFrame*, unsigned short, art::JValue*)+344)
#36 pc 00000000002792bc /system/lib64/libart.so (bool art::interpreter::DoCall<false, false>(art::ArtMethod*, art::Thread*, art::ShadowFrame&, art::Instruction const*, unsigned short, art::JValue*)+968)
#37 pc 0000000000524710 /system/lib64/libart.so (MterpInvokeVirtual+588)
#38 pc 0000000000547014 /system/lib64/libart.so (ExecuteMterpImpl+14228)
#39 pc 0000000000c3779e /system/framework/boot-framework.vdex (com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run+22)
#40 pc 0000000000252fc0 /system/lib64/libart.so (_ZN3art11interpreterL7ExecuteEPNS_6ThreadERKNS_20CodeItemDataAccessorERNS_11ShadowFrameENS_6JValueEb.llvm.3783761849+488)
#41 pc 0000000000514fa4 /system/lib64/libart.so (artQuickToInterpreterBridge+1020)
#42 pc 000000000055dafc /system/lib64/libart.so (art_quick_to_interpreter_bridge+92)
#43 pc 0000000000bf9920 /system/framework/arm64/boot-framework.oat (offset 0x3d0000) (com.android.internal.os.ZygoteInit.main+3088)
#44 pc 0000000000554c4c /system/lib64/libart.so (art_quick_invoke_static_stub+604)
#45 pc 00000000000cf6e8 /system/lib64/libart.so (art::ArtMethod::Invoke(art::Thread*, unsigned int*, unsigned int, art::JValue*, char const*)+232)
#46 pc 000000000045c840 /system/lib64/libart.so (art::(anonymous namespace)::InvokeWithArgArray(art::ScopedObjectAccessAlreadyRunnable const&, art::ArtMethod*, art::(anonymous namespace)::ArgArray*, art::JValue*, char const*)+104)
#47 pc 000000000045c4a0 /system/lib64/libart.so (art::InvokeWithVarArgs(art::ScopedObjectAccessAlreadyRunnable const&, _jobject*, _jmethodID*, std::__va_list)+424)
#48 pc 0000000000361b60 /system/lib64/libart.so (art::JNI::CallStaticVoidMethodV(_JNIEnv*, _jclass*, _jmethodID*, std::__va_list)+652)
#49 pc 00000000000b2e24 /system/lib64/libandroid_runtime.so (_JNIEnv::CallStaticVoidMethod(_jclass*, _jmethodID*, ...)+120)
#50 pc 00000000000b57a8 /system/lib64/libandroid_runtime.so (android::AndroidRuntime::start(char const*, android::Vector<android::String8> const&, bool)+756)
#51 pc 00000000000022f8 /system/bin/app_process64 (main+1380)
#52 pc 00000000000aca4c /system/lib64/libc.so (__libc_init+88)
Lost connection to device.
Exited (sigterm)
Thank you for helping a noob..

Related

Unhandled Exception: type 'List<dynamic>' is not a subtype of type 'Map<String, dynamic>'

UPDATE: Thanks to #Rjulcaa answer My map is now a List, however the List wasn't displayed on the UI. I turns that I needed to handle the future with a FutureBuilder, so in case anyone faces this problem remember to add a FutureBuilder to the body of your UI and on the builder return the widget you want to be displayed.
I'm making a todo list tutorial, I'm trying to add the feature of encoding on a JSON my todoList the save it on a sharedPreferences, and when I start the app retrieve it on the screen
This is my TODO class
class Todo {
Todo ({this.title,this.isDone = false});
String title;
bool isDone;
//Decode method to convert a Json String into a Dynamic object
Todo.fromJson(Map <String, dynamic> json)
: title = json ["title"],
isDone = json ["isDone"];
Map <String,dynamic> toJson() =>
{
"title" : title,
"isDone" : isDone
};
}
This is my screen
class _TodoListScreenState extends State<TodoListScreen> {
List<Todo> todos = [];
#override
void initState() {
super.initState();
_getTodoFromSharedPreferences();
}
//updates the state of the checkbox and reflects it on the UI
_toggleTodo(Todo todo, bool isChecked) {
setState(() {
todo.isDone = isChecked;
});
}
_addTodo() async {
final todo = await showDialog<Todo>(
context: context,
builder:(BuildContext context) { // <- Here you draw the Dialog
return NewTodoDialog();
},
);
if (todo != null) {
setState(() {
todos.add(todo);
_saveTodo(todos);
print(todos.length);
});
}
}
_saveTodo(List<Todo> todo) async{
final String newTodo = jsonEncode(todo);
setSharedPreferences(newTodo);
}
_getTodoFromSharedPreferences () async {
final prefs = await SharedPreferences.getInstance();
final savedTodo = prefs.getString("savedTodo");
if (savedTodo == null) {return null;} else {
Map MapofTodos = jsonDecode(savedTodo);
for (var i = 0; i < MapofTodos.length; ++i) {
var o = MapofTodos[i];
setState(() {
Todo todo = Todo.fromJson(o);
todos.add(todo);
});
}
}
}
setSharedPreferences (String newTodo ) async{
final prefs = await SharedPreferences.getInstance();
await prefs.setString("savedTodo", newTodo );
print(newTodo);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(backgroundColor:Colors.deepPurple[900] ,
title: Text('Todo List')),
body: TodoList(
todos: todos,
onTodoToggle: _toggleTodo,
),
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.purpleAccent[700],
child: Icon(Icons.add),
onPressed: _addTodo,
),
);
}
}
when I run the app i get this error
E/flutter ( 7476): [ERROR:flutter/lib/ui/ui_dart_state.cc(148)]
Unhandled Exception: type 'List<dynamic>' is not a subtype of type
'Map<dynamic, dynamic>'
E/flutter ( 7476): #0
_TodoListScreenState._getTodoFromSharedPreferences
(package:flutter_todo/UI/todo_list_screen.dart:70:11)
E/flutter ( 7476): <asynchronous suspension>
E/flutter ( 7476): #1 _TodoListScreenState.initState
(package:flutter_todo/UI/todo_list_screen.dart:29:6)
E/flutter ( 7476): #2 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3851:58)
E/flutter ( 7476): #3 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #4 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #5 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #6 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #7 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #8 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #9 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #10 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #11 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #12 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #13 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #14 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #15 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #16 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #17 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #18 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #19 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #20 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #21 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #22 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #23 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #24 SingleChildRenderObjectElement.mount
(package:flutter/src/widgets/framework.dart:4881:14)
E/flutter ( 7476): #25 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #26 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #27 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #28 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #29 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #30 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #31 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #32 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #33 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #34 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #35 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #36 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #37 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #38 Element.inflateWidget
(package:flutter/src/widgets/framework.dart:2960:14)
E/flutter ( 7476): #39 Element.updateChild
(package:flutter/src/widgets/framework.dart:2763:12)
E/flutter ( 7476): #40 ComponentElement.performRebuild
(package:flutter/src/widgets/framework.dart:3752:16)
E/flutter ( 7476): #41 Element.rebuild
(package:flutter/src/widgets/framework.dart:3564:5)
E/flutter ( 7476): #42 ComponentElement._firstBuild
(package:flutter/src/widgets/framework.dart:3721:5)
E/flutter ( 7476): #43 StatefulElement._firstBuild
(package:flutter/src/widgets/framework.dart:3869:11)
E/flutter ( 7476): #44 ComponentElement.mount
(package:flutter/src/widgets/framework.dart:3716:5)
E/flutter ( 7476): #45 Ele
I tried to change the List to a Map but didn't succeed
I have succeeded on everything except returning the widget to the screen.
Help me, please :c
I faced this problem before because I wanted to save an array object in shared preferences. You can try this.
//Save you array object as an array of Strings in Shared Preferences
void _saveTodo(List<Todo> todo) async{
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
sharedPreferences.setStringList("savedTodo", _mapTodoData(todo));
}
}
Transform the JSON into an array of Strings
List<String> _mapTodoData(List<dynamic> todos) async{
try {
var res = todos.map((v) => json.encode(v)).toList();
return res;
} catch (err) {
// Just in case
return [];
}
}
}
if you want to get and transform the data in a List of Todo objects
void loadData() async {
SharedPreferences sharedPreferences = await SharedPreferences.getInstance();
final todoArray = _decodeTodoData(sharedPreferences.getStringList("savedTodo"))
//This is your array :) -> todoArray
}
List<Todo> _decodeTodoData(List<String> todos) {
try {
//Transforming List<String> to Json
var result = todos.map((v) => json.decode(v)).toList();
//Transforming the Json into Array<Todo>
var todObjects = result.map((v) => Todo.fromJson(v)).toList();
return todObjects;
} catch (error) {
return [];
}
}
}
This worked for me, I really struggled with this problem.
I Hope this works for you too.
Here you're trying to iterate over a Map which is not possible because only possible Iterables objects are Set,List and Queue.
// Map MapofTodos = jsonDecode(savedTodo);
//Try to debug it first first and see what type it's returning
print(jsonDecode(savedTodo).runtimeType);
I faced the same issue during app development in dart. The issue with json decoding techniques or might be json conversion.
I have done work around for creating the method as passing the parameter as
getCardData(data[0]["cardContent"][0]["cardData"] as List),
List<String> getCardData(data) {
List<String> _cardInfo = [];
for (int i = 0; i < data.length; i++) {
_cardInfo.add(data[i] as String);
}
return _cardInfo;
}

Drag and Drop List- method 'call' was called on null

I'm trying to make a drag and drop list using flutter_list_drag_and_drop 0.1.6. I've looked for examples of how to implement it, but there aren't any out yet for this specifically, so much of it has been trial and error. Anyway, when I run the app, it gives me an error when trying to drag one of the MyDraggables for the list view. It's says "Exception caught by gesture", "The following NoSuchMethodError was thrown while handling a gesture: The method 'call' was called on null," "Receiver: null", "Tried calling: call(Instance of 'Offset').
I've tried debugging but can not locate where exactly this is crashing. The feedback for the draggable widget is appearing, but stays stuck in place.
```
Widget _buildDragDrop(double _screenHeight, double _screenWidth){
return DragAndDropList(_nonDelList.getList(),
canBeDraggedTo: (int i, int j) {
print("drag to");
// _nonDelList.changePos(_nonDelList.getTaskAt(i), j);
return true;
},
itemBuilder: (BuildContext _context, Task _t1) {
print('Entered Item Builder');
return _buildTask(_t1, _screenHeight, _screenWidth);
},
onDragFinish: (int i, int j){
print('Drag finished');
_nonDelList.changePos(_nonDelList.getTaskAt(i), j);
print('Drag finished 2');
},
dragElevation: 1.5,
);
}
Widget _buildTask(Task _t, double _screenHeight, double
_screenWidth){
final bool alreadyCompleted = !(_t.getPressed());
return new MyDraggable(
child: new ListTile(
title: new Text(_t.getEntry()),
trailing: new Icon(
alreadyCompleted ? Icons.check_box :
Icons.check_box_outline_blank,
color: alreadyCompleted ? _t.getColor() : Colors.black,
),
subtitle: new Text(_t.getDescription()),
),
onDragStarted: (){
print('Started Drag');
},
onMyDraggableCanceled: (Velocity v, Offset o){
print('Drag Canceled');
},
feedback: Material(
shape: CircleBorder(),
child: new InkResponse(
child: Container(
width: _screenWidth / 15.0,
height: _screenWidth / 15.0,
color: Colors.red,
),
),
),
);
}
```
I would expect the list tile to drag and drop in place. The only thing that is happening however, is my feedback is appearing at the top left of the list tile when I start the drag, and then this error is immediately spit out. Also, 'Started Drag' and 'Drag Canceled' are not print out, the only thing that is printing is 'Entered Item Builder.'
I welcome and appreciate all help!
Thanks in advance!
EDIT (Stacktrace)
I/flutter ( 2974): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter ( 2974): The following NoSuchMethodError was thrown while handling a gesture:
I/flutter ( 2974): The method 'call' was called on null.
I/flutter ( 2974): Receiver: null
I/flutter ( 2974): Tried calling: call(Instance of 'Offset')
I/flutter ( 2974):
I/flutter ( 2974): When the exception was thrown, this was the stack:
I/flutter ( 2974): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 2974): #1 DragAvatar.updateDrag
package:flutter_list_drag_and_drop/my_draggable.dart:547
I/flutter ( 2974): #2 new DragAvatar
package:flutter_list_drag_and_drop/my_draggable.dart:498
I/flutter ( 2974): #3 MyDraggableState._startDrag
package:flutter_list_drag_and_drop/my_draggable.dart:328
I/flutter ( 2974): #4 MultiDragGestureRecognizer._startDrag.<anonymous closure>
package:flutter/…/gestures/multidrag.dart:263
I/flutter ( 2974): #5 GestureRecognizer.invokeCallback
package:flutter/…/gestures/recognizer.dart:120
I/flutter ( 2974): #6 MultiDragGestureRecognizer._startDrag
package:flutter/…/gestures/multidrag.dart:263
I/flutter ( 2974): #7 MultiDragGestureRecognizer.acceptGesture.<anonymous closure>
package:flutter/…/gestures/multidrag.dart:253
I/flutter ( 2974): #8 _ImmediatePointerState.accepted
package:flutter/…/gestures/multidrag.dart:315
I/flutter ( 2974): #9 MultiDragGestureRecognizer.acceptGesture
package:flutter/…/gestures/multidrag.dart:253
I/flutter ( 2974): #10 GestureArenaManager._resolveInFavorOf
package:flutter/…/gestures/arena.dart:263
I/flutter ( 2974): #11 GestureArenaManager._resolve
package:flutter/…/gestures/arena.dart:222
I/flutter ( 2974): #12 GestureArenaEntry.resolve
package:flutter/…/gestures/arena.dart:52
I/flutter ( 2974): #13 MultiDragPointerState.resolve
package:flutter/…/gestures/multidrag.dart:62
I/flutter ( 2974): #14 _ImmediatePointerState.checkForResolutionAfterMove
package:flutter/…/gestures/multidrag.dart:310
I/flutter ( 2974): #15 MultiDragPointerState._move
package:flutter/…/gestures/multidrag.dart:81
I/flutter ( 2974): #16 MultiDragGestureRecognizer._handleEvent
package:flutter/…/gestures/multidrag.dart:227
I/flutter ( 2974): #17 PointerRouter._dispatch
package:flutter/…/gestures/pointer_router.dart:73
I/flutter ( 2974): #18 PointerRouter.route
package:flutter/…/gestures/pointer_router.dart:101
I/flutter ( 2974): #19 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent
package:flutter/…/gestures/binding.dart:214
I/flutter ( 2974): #20 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent
package:flutter/…/gestures/binding.dart:192
I/flutter ( 2974): #21 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent
package:flutter/…/gestures/binding.dart:149
I/flutter ( 2974): #22 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue
I/flutter ( 2974): #23 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket
package:flutter/…/gestures/binding.dart:85
I/flutter ( 2974): #27 _invoke1 (dart:ui/hooks.dart:223:10)
I/flutter ( 2974): #28 _dispatchPointerDataPacket (dart:ui/hooks.dart:144:5)
I/flutter ( 2974): (elided 3 frames from package dart:async)
I/flutter ( 2974):
I/flutter ( 2974): Handler: onStart
I/flutter ( 2974): Recognizer:
I/flutter ( 2974): ImmediateMultiDragGestureRecognizer#774eb
The stack trace says:
I/flutter ( 2974): When the exception was thrown, this was the stack:
I/flutter ( 2974): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:50:5)
I/flutter ( 2974): #1 DragAvatar.updateDrag
package:flutter_list_drag_and_drop/my_draggable.dart:547
Okay, so the null pointer exception occurred there. Let's take a look at the code:
onMove(globalPosition);
That fits the error message, which was:
I/flutter ( 2974): Tried calling: call(Instance of 'Offset')
So globalPosition is likely an Offset, and onMove must be an object. Let's search in the code where onMove was supposed to be set:
DragAvatar({
#required this.overlayState,
...
this.onMove,
(line 491)
which (omitting some steps) appears to be obtained from:
const MyDraggable({
Key key,
#required this.child,
#required this.feedback,
...
this.onMove
(line 101)
I don't see anywhere else where onMove is otherwise set. It looks like there's probably a bug that DragAvatar.updateDrag unconditionally calls onMove, that onMove isn't marked #required initially, or that onMove isn't initialized to some default.
At any rate, try supplying an onMove callback when constructing MyDraggable.
(Alternatively, perhaps consider using the official ReorderableListView class, which the flutter_list_drag_and_drop package page even refers to.)

How to run task in background even if the app is closed and get the latest result generated by the task and display it when app is opened?

I want to to create a step counter app in flutter so i used Flutter pedometer plugin and it worked perfectly, but i want to run this plugin every time to calculate user steps even if the main app is closed .
I found that i can use dart isolates to create a task that can run in another thread away from main thread and communicate between them through ports .
String _stepCountValue = '0';
ReceivePort _receivePort;
Isolate isolate;
iniState() {
super.initState();
_start();
}
void _start() async {
_receivePort = ReceivePort();
isolate = await Isolate.spawn(initPlatformState,
_receivePort.sendPort);
_receivePort.listen((data) {
print(data);
setState(() {
_stepCountValue = "$data";
});
}, onDone: () {
print("done!");
});
}
static void initPlatformState(SendPort sendPort) async {
Pedometer pedometer = new Pedometer();
pedometer.stepCountStream.listen((int stepCountValue) {
print("------------------> $stepCountValue");
sendPort.send(stepCountValue);
}, onError: (error){print(error);}, onDone: (){}, cancelOnError:
true);
}
I expect the output to be the number of user steps .
but i get that error
I/flutter (26151): ══╡ EXCEPTION CAUGHT BY SERVICES LIBRARY ╞══════════════════════════════════════════════════════════
I/flutter (26151): The following _CompileTimeError was thrown while activating platform stream on channel
I/flutter (26151): pedometer.eventChannel:
I/flutter (26151): error: native function 'Window_sendPlatformMessage' (4 arguments) cannot be found
I/flutter (26151): When the exception was thrown, this was the stack:
I/flutter (26151): #0 Window.sendPlatformMessage (dart:ui/window.dart:868:9)
I/flutter (26151): #1 BinaryMessages._sendPlatformMessage (package:flutter/src/services/platform_messages.dart:46:15)
I/flutter (26151): #2 BinaryMessages.send (package:flutter/src/services/platform_messages.dart:97:12)
I/flutter (26151): #3 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:295:50)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #4 EventChannel.receiveBroadcastStream.<anonymous closure> (package:flutter/src/services/platform_channel.dart:490:29)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #12 StepCounterState.initPlatformState (package:stepcounter/main.dart:59:30)
I/flutter (26151): <asynchronous suspension>
I/flutter (26151): #13 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:303:17)
I/flutter (26151): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:171:12)
I/flutter (26151): (elided 7 frames from package dart:async)

how to change app theme in runtime in Flutter?

In my simple project , there is a button to change theme form light to dark and vice versa as below :
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async';
void main() => runApp(MyApp());
class MyApp extends StatefulWidget {
#override
MyAppState createState() {
return new MyAppState();
}
}
class MyAppState extends State<MyApp> {
Future<bool> load(String key, bool defaultValue) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
bool state = prefs.getBool(key) ?? defaultValue;
return state;
}
Future<void> save(String key, bool value) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
prefs.setBool(key, value);
}
bool state;
#override
Widget build(BuildContext context) {
load("themeKey", false).then((bool value) {
state = value;
});
debugPrint(
"..............state is : " + state.toString() + "...............");
return MaterialApp(
theme: state ? ThemeData.light() : ThemeData.dark(),
home: Scaffold(
body: Container(
child: RaisedButton(
child: Text("change"),
onPressed: () {
setState(() {
state = !state;
});
save("themeKey", state);
},
),
),
),
);
}
}
I use shared_preferences plugin to save the current theme state for the next app launch , but there is a problem it seems that app loads before shared preference loads so i am getting this exception:
Launching lib\main.dart on C1905 in debug mode...
Built build\app\outputs\apk\debug\app-debug.apk.
I/flutter ( 8045): ..............state is : null...............
I/flutter ( 8045): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 8045): The following assertion was thrown building MyApp(dirty, state: MyAppState#6774f):
I/flutter ( 8045): Failed assertion: boolean expression must not be null
I/flutter ( 8045): Either the assertion indicates an error in the framework itself, or we should provide substantially
I/flutter ( 8045): more information in this error message to help you determine and fix the underlying cause.
I/flutter ( 8045): In either case, please report this assertion by filing a bug on GitHub:
I/flutter ( 8045): https://github.com/flutter/flutter/issues/new?template=BUG.md
I/flutter ( 8045): When the exception was thrown, this was the stack:
I/flutter ( 8045): #0 MyAppState.build (package:test_shared_preferenced/main.dart:36:14)
I/flutter ( 8045): #1 StatefulElement.build (package:flutter/src/widgets/framework.dart:3787:27)
I/flutter ( 8045): #2 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3699:15)
I/flutter ( 8045): #3 Element.rebuild (package:flutter/src/widgets/framework.dart:3547:5)
I/flutter ( 8045): #4 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3679:5)
I/flutter ( 8045): #5 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:3826:11)
I/flutter ( 8045): #6 ComponentElement.mount (package:flutter/src/widgets/framework.dart:3674:5)
I/flutter ( 8045): #7 Element.inflateWidget (package:flutter/src/widgets/framework.dart:2950:14)
I/flutter ( 8045): #8 Element.updateChild (package:flutter/src/widgets/framework.dart:2753:12)
I/flutter ( 8045): #9 RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:909:16)
I/flutter ( 8045): #10 RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:880:5)
I/flutter ( 8045): #11 RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:826:17)
I/flutter ( 8045): #12 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2266:19)
I/flutter ( 8045): #13 RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:825:13)
I/flutter ( 8045): #14 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&SemanticsBinding&RendererBinding&WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:712:7)
I/flutter ( 8045): #15 runApp (package:flutter/src/widgets/binding.dart:756:7)
I/flutter ( 8045): #16 main (package:test_shared_preferenced/main.dart:5:16)
I/flutter ( 8045): #17 _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:289:19)
I/flutter ( 8045): #18 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:171:12)
I/flutter ( 8045): ════════════════════════════════════════════════════════════════════════════════════════════════════
so what should i do in this situation , please help
The load method is returns a Future that will run asynchronously from the rest of your code. When execution reaches debugPrint or the subsequent return statement, you cannot be guaranteed that the then block has completed its execution. The error you are receiving confirms this. The state boolean has not been set to a value yet - it is still null.
Using a FutureBuilder can help you handle cases where you are waiting on a Future to build your widget tree.
https://www.dartlang.org/tutorials/language/futures is worthwhile reading.

Getting a configuration engine error when trying hot restart in flutter application

I'm learning streams/bloc pattern in dart/flutter and can't pinpoint where the error is coming from when I try to run my app. I assume the stream is getting hung up somewhere judging by the async errors. I am usingdispose() and closing out the streams inside it. Any help would be appreciated.
Here is the code. I put it all in one big chunk but commented which file each of the code chunks is from:
// bloc.dart
import 'dart:async';
import 'validators.dart';
class Bloc extends Validators {
final _email = new StreamController<String>();
final _password = new StreamController<String>();
// Add data to stream
Stream<String> get email => _email.stream.transform(validateEmail);
Stream<String> get password => _password.stream.transform(validatePassword);
// Change Data
Function(String) get changeEmail => _email.sink.add;
Function(String) get changePassword => _password.sink.add;
dispose() {
_email.close();
_password.close();
}
}
final bloc = Bloc();
// login_screen.dart
import 'package:flutter/material.dart';
import '../blocs/bloc.dart';
class LoginScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(20.0),
child: Column(
children: [
emailField(),
passwordField(),
Container(
margin: EdgeInsets.only(top: 25.0),
),
raisedButton()
],
));
}
Widget emailField() {
return StreamBuilder(
stream: bloc.email,
builder: (context, snapshot) {
return TextField(
onChanged: bloc.changeEmail,
keyboardType: TextInputType.emailAddress,
decoration: InputDecoration(
hintText: 'ardon#exampl.com',
labelText: 'Enter your email!',
errorText: snapshot.error),
);
});
}
Widget passwordField() {
return TextField(
obscureText: true,
decoration: InputDecoration(hintText: 'password', labelText: 'password'),
);
}
Widget raisedButton() {
return RaisedButton(
child: Text('Login'),
color: Colors.blue,
onPressed: () {},
);
}
}
// validation.dart
import 'dart:async';
class Validators {
final validateEmail =
StreamTransformer<String, String>.fromHandlers(handleData: (email, sink) {
if (email.contains('#')) {
sink.add(email);
} else {
sink.addError('Please enter valid email');
}
});
final validatePassword = StreamTransformer<String, String>.fromHandlers(
handleData: (password, sink) {
if (password.length > 4) {
sink.add(password);
} else {
sink.addError('Please enter the right number of characters');
}
});
}
Here is the error I am getting when I try to hot restart my app:
⣯[VERBOSE-2:shell.cc(181)] Dart Error: Can't load Kernel binary: Invalid kernel binary format version.
[VERBOSE-2:engine.cc(158)] Could not prepare to run the isolate.
[VERBOSE-2:engine.cc(117)] Engine not prepare and launch isolate.
Error -32000 received from application: Could not run configuration in engine.
JSON-RPC error -32000: Could not run configuration in engine.
package:json_rpc_2/src/client.dart 110:64 Client.sendRequest
package:json_rpc_2/src/peer.dart 68:15 Peer.sendRequest
package:flutter_tools/src/vmservice.dart 293:13 VMService._sendRequest
package:flutter_tools/src/vmservice.dart 842:12 VM.invokeRpcRaw
===== asynchronous gap ===========================
package:flutter_tools/src/vmservice.dart 865:49 VM.invokeRpc
===== asynchronous gap ===========================
package:flutter_tools/src/vmservice.dart 932:12 VM.runInView
package:flutter_tools/src/vmservice.dart 1439:20 FlutterView.runFromSource
===== asynchronous gap ===========================
package:flutter_tools/src/run_hot.dart 379:18 HotRunner._launchInView
===== asynchronous gap ===========================
package:flutter_tools/src/run_hot.dart 390:13 HotRunner._launchFromDevFS
===== asynchronous gap ===========================
package:flutter_tools/src/run_hot.dart 442:11 HotRunner._restartFromSources
===== asynchronous gap ===========================
package:flutter_tools/src/run_hot.dart 505:15 HotRunner.restart
===== asynchronous gap ===========================
package:flutter_tools/src/run_hot.dart 282:44 HotRunner.handleTerminalCommand
===== asynchronous gap ===========================
package:flutter_tools/src/resident_runner.dart 754:15 ResidentRunner.processTerminalInput
===== asynchronous gap ===========================
dart:async/zone.dart 1132:38 _rootRunUnary
dart:async/zone.dart 1029:19 _CustomZone.runUnary
dart:async/zone.dart 931:7 _CustomZone.runUnaryGuarded
dart:async/stream_impl.dart 336:11 _BufferingStreamSubscription._sendData
dart:async/stream_impl.dart 263:7 _BufferingStreamSubscription._add
dart:async/broadcast_stream_controller.dart 379:20 _SyncBroadcastStreamController._sendData
dart:async/broadcast_stream_controller.dart 254:5 _BroadcastStreamController.add
dart:async/broadcast_stream_controller.dart 480:11 _AsBroadcastStreamController.add
dart:async/zone.dart 1132:38 _rootRunUnary
dart:async/zone.dart 1029:19 _CustomZone.runUnary
dart:async/zone.dart 931:7 _CustomZone.runUnaryGuarded
dart:async/stream_impl.dart 336:11 _BufferingStreamSubscription._sendData
dart:async/stream_impl.dart 263:7 _BufferingStreamSubscription._add
dart:async/stream_transformers.dart 68:11 _SinkTransformerStreamSubscription._add
dart:async/stream_transformers.dart 15:11 _EventSinkWrapper.add
dart:convert/string_conversion.dart 268:11 _StringAdapterSink.add
dart:convert/string_conversion.dart 273:7 _StringAdapterSink.addSlice
dart:convert/string_conversion.dart 348:20 _Utf8ConversionSink.addSlice
dart:convert/ascii.dart 278:17 _ErrorHandlingAsciiDecoderSink.addSlice
dart:convert/ascii.dart 264:5 _ErrorHandlingAsciiDecoderSink.add
dart:convert/chunked_conversion.dart 86:18 _ConverterStreamEventSink.add
dart:async/stream_transformers.dart 120:24 _SinkTransformerStreamSubscription._handleData
dart:async/zone.dart 1132:38 _rootRunUnary
dart:async/zone.dart 1029:19 _CustomZone.runUnary
dart:async/zone.dart 931:7 _CustomZone.runUnaryGuarded
dart:async/stream_impl.dart 336:11 _BufferingStreamSubscription._sendData
dart:async/stream_impl.dart 263:7 _BufferingStreamSubscription._add
dart:async/stream_controller.dart 763:19 _SyncStreamController._sendData
dart:async/stream_controller.dart 639:7 _StreamController._add
dart:async/stream_controller.dart 585:5 _StreamController.add
dart:io/runtime/binsocket_patch.dart 1714:41 _Socket._onData
dart:async/zone.dart 1136:13 _rootRunUnary
dart:async/zone.dart 1029:19 _CustomZone.runUnary
dart:async/zone.dart 931:7 _CustomZone.runUnaryGuarded
dart:async/stream_impl.dart 336:11 _BufferingStreamSubscription._sendData
dart:async/stream_impl.dart 263:7 _BufferingStreamSubscription._add
dart:async/stream_controller.dart 763:19 _SyncStreamController._sendData
dart:async/stream_controller.dart 639:7 _StreamController._add
dart:async/stream_controller.dart 585:5 _StreamController.add
dart:io/runtime/binsocket_patch.dart 1276:33 new _RawSocket.<fn>
dart:io/runtime/binsocket_patch.dart 819:14 _NativeSocket.issueReadEvent.issue
dart:async/schedule_microtask.dart 41:21 _microtaskLoop
dart:async/schedule_microtask.dart 50:5 _startMicrotaskLoop
dart:isolate/runtime/libisolate_patch.dart 115:13 _runPendingImmediateCallback
dart:isolate/runtime/libisolate_patch.dart 172:5 _RawReceivePortImpl._handleMessage
edit: When I do a hot reload instead of a hot restart, I get this error:
Initializing hot reload... ⣟Hot reload failed: type 'TimeoutException' is not a subtype of type 'Map<String, dynamic>'
#0 HotRunner._reloadSources.<anonymous closure> (package:flutter_tools/src/run_hot.dart:587:45)
#1 _rootRunUnary (dart:async/zone.dart:1132:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#3 _FutureListener.handleError (dart:async/future_impl.dart:147:20)
#4 Future._propagateToListeners.handleError (dart:async/future_impl.dart:654:47)
#5 Future._propagateToListeners (dart:async/future_impl.dart:675:24)
#6 Future._completeError (dart:async/future_impl.dart:494:5)
#7 Future.wait.handleError (dart:async/future.dart:379:18)
#8 _rootRunBinary (dart:async/zone.dart:1144:38)
#9 _CustomZone.runBinary (dart:async/zone.dart:1037:19)
#10 _FutureListener.handleError (dart:async/future_impl.dart:143:20)
#11 Future._propagateToListeners.handleError (dart:async/future_impl.dart:654:47)
#12 Future._propagateToListeners (dart:async/future_impl.dart:675:24)
#13 Future._completeError (dart:async/future_impl.dart:494:5)
#14 _SyncCompleter._completeError (dart:async/future_impl.dart:55:12)
#15 _Completer.completeError (dart:async/future_impl.dart:27:5)
#16 _AsyncAwaitCompleter.completeError (dart:async/runtime/libasync_patch.dart:40:18)
#17 Isolate.reloadSources (package:flutter_tools/src/vmservice.dart)
<asynchronous suspension>
#18 FlutterDevice.reloadSources (package:flutter_tools/src/resident_runner.dart:144:66)
#19 HotRunner._reloadSources (package:flutter_tools/src/run_hot.dart:579:67)
<asynchronous suspension>
#20 HotRunner.restart (package:flutter_tools/src/run_hot.dart:520:24)
<asynchronous suspension>
#21 HotRunner.handleTerminalCommand (package:flutter_tools/src/run_hot.dart:282:44)
<asynchronous suspension>
#22 ResidentRunner.processTerminalInput (package:flutter_tools/src/resident_runner.dart:754:15)
<asynchronous suspension>
#23 _rootRunUnary (dart:async/zone.dart:1132:38)
#24 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#25 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#26 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#27 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#28 _SyncBroadcastStreamController._sendData (dart:async/broadcast_stream_controller.dart:379:20)
#29 _BroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:254:5)
#30 _AsBroadcastStreamController.add (dart:async/broadcast_stream_controller.dart:480:11)
#31 _rootRunUnary (dart:async/zone.dart:1132:38)
#32 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#33 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#34 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#35 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#36 _SinkTransformerStreamSubscription._add (dart:async/stream_transformers.dart:68:11)
#37 _EventSinkWrapper.add (dart:async/stream_transformers.dart:15:11)
#38 _StringAdapterSink.add (dart:convert/string_conversion.dart:268:11)
#39 _StringAdapterSink.addSlice (dart:convert/string_conversion.dart:273:7)
#40 _Utf8ConversionSink.addSlice (dart:convert/string_conversion.dart:348:20)
#41 _ErrorHandlingAsciiDecoderSink.addSlice (dart:convert/ascii.dart:278:17)
#42 _ErrorHandlingAsciiDecoderSink.add (dart:convert/ascii.dart:264:5)
#43 _ConverterStreamEventSink.add (dart:convert/chunked_conversion.dart:86:18)
#44 _SinkTransformerStreamSubscription._handleData (dart:async/stream_transformers.dart:120:24)
#45 _rootRunUnary (dart:async/zone.dart:1132:38)
#46 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#47 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#48 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#49 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#50 _SyncStreamController._sendData (dart:async/stream_controller.dart:763:19)
#51 _StreamController._add (dart:async/stream_controller.dart:639:7)
#52 _StreamController.add (dart:async/stream_controller.dart:585:5)
#53 _Socket._onData (dart:io/runtime/binsocket_patch.dart:1714:41)
#54 _rootRunUnary (dart:async/zone.dart:1136:13)
#55 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#56 _CustomZone.runUnaryGuarded (dart:async/zone.dart:931:7)
#57 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:336:11)
#58 _BufferingStreamSubscription._add (dart:async/stream_impl.dart:263:7)
#59 _SyncStreamController._sendData (dart:async/stream_controller.dart:763:19)
#60 _StreamController._add (dart:async/stream_controller.dart:639:7)
#61 _StreamController.add (dart:async/stream_controller.dart:585:5)
#62 new _RawSocket.<anonymous closure> (dart:io/runtime/binsocket_patch.dart:1276:33)
#63 _NativeSocket.issueReadEvent.issue (dart:io/runtime/binsocket_patch.dart:819:14)
#64 _microtaskLoop (dart:async/schedule_microtask.dart:41:21)
#65 _startMicrotaskLoop (dart:async/schedule_microtask.dart:50:5)
#66 _runPendingImmediateCallback (dart:isolate/runtime/libisolate_patch.dart:115:13)
#67 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:172:5)
A case where you'll frequently run into this is if you're building your own engine from source, and using it via flutter's --local-engine option.
Dart code in a Flutter app is initially compiled through the Dart kernel compiler, which emits a .dill file in an intermediate format. This intermediate format includes an identifier that the Dart VM in the Flutter engine uses to validate that it's compatible with that VM version. The root cause of an Invalid kernel binary format version error message is that the .dill file in question was generated with an incompatible version of the kernel compiler.
To resolve this, after rebuilding the engine for your device (e.g. android_debug_unopt), you'll want to ensure that you've also rebuilt the associated host toolchain (e.g. host_debug_unopt).
If you're seeing this in other cases, it's almost certainly a bug, and I'd definitely encourage you to open an issue against Flutter.
There was a bug fixed very recently that resulted in this error message https://github.com/flutter/flutter/issues/21348
I would expect this to be included in the latest Flutter dev and master channel.
To switch to the dev channel use
flutter channel dev
flutter doctor
update
(from https://github.com/flutter/flutter/issues/22964#issuecomment-429071970)
import './src/app.dart'; in lib/main.dart is the culprit.
lib/main.dart must not contain relative imports and must not be imported from other files
https://github.com/dart-lang/sdk#33076
was just fixed but it will take a while until it lands in Flutter.

Resources