I was making 2 scene with google Maps and drawing polyline on the map, the apps have no problem running and everything working fine, however on the debug there is this big stack of error in debug which I have no idea what it meant, can anyone tell me what is this ? It is kind of concerning for me
Below is the error on the debug,
════════ Exception caught by rendering library ═════════════════════════════════
Failed to rasterize a picture: unable to create render target at specified size.
The callstack when the image was created was:
#0 new Image._.<anonymous closure> (dart:ui/painting.dart:1670:32)
#1 new Image._ (dart:ui/painting.dart:1672:6)
#2 Scene.toImageSync (dart:ui/compositing.dart:34:18)
#3 OffsetLayer.toImageSync
layer.dart:1497
#4 _RenderSnapshotWidget._paintAndDetachToImage
snapshot_widget.dart:315
#5 _RenderSnapshotWidget.paint
snapshot_widget.dart:345
#6 RenderObject._paintWithContext
object.dart:2853
#7 PaintingContext.paintChild
object.dart:253
#8 RenderProxyBoxMixin.paint
#9 _ZoomEnterTransitionPainter.paint
page_transitions_theme.dart:866
#10 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#11 RenderObject._paintWithContext
object.dart:2853
#12 PaintingContext.paintChild
object.dart:253
#13 RenderProxyBoxMixin.paint
proxy_box.dart:144
#14 _ZoomExitTransitionPainter.paint
page_transitions_theme.dart:938
#15 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#16 RenderObject._paintWithContext
object.dart:2853
#17 PaintingContext.paintChild
object.dart:253
#18 RenderProxyBoxMixin.paint
proxy_box.dart:144
#19 _ZoomEnterTransitionPainter.paint
page_transitions_theme.dart:866
#20 _RenderSnapshotWidget.paint
snapshot_widget.dart:335
#21 RenderObject._paintWithContext
object.dart:2853
#22 PaintingContext.paintChild
object.dart:253
#23 RenderProxyBoxMixin.paint
proxy_box.dart:144
#24 RenderObject._paintWithContext
object.dart:2853
#25 PaintingContext._repaintCompositedChild
object.dart:169
#26 PaintingContext.repaintCompositedChild
object.dart:112
#27 PipelineOwner.flushPaint
object.dart:1137
#28 RendererBinding.drawFrame
binding.dart:518
#29 WidgetsBinding.drawFrame
binding.dart:865
#30 RendererBinding._handlePersistentFrameCallback
binding.dart:381
#31 SchedulerBinding._invokeFrameCallback
binding.dart:1289
#32 SchedulerBinding.handleDrawFrame
binding.dart:1218
#33 SchedulerBinding._handleDrawFrame
binding.dart:1076
#34 _invoke (dart:ui/hooks.dart:145:13)
#35 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:338:5)
#36 _drawFrame (dart:ui/hooks.dart:112:31)
The relevant error-causing widget was
MaterialApp
Edit:
Here's the packages and code of the scene that triggered the error in the debug, for extra information, the error did not triggered consistently. I have no idea what trigered it, the materialapp exist on the home page. I use navigator function to switch scene
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_in_flutter/location_service.dart';
import 'package:geolocator/geolocator.dart';
import 'package:label_marker/label_marker.dart';
StreamSubscription<Position>? userStreamlocation;
Position? streamResult;
class navScreen extends StatefulWidget
{
final String userOrigin;
final String userGoal;
navScreen({Key? mykey, required this.userOrigin, required this.userGoal});
#override
State<navScreen> createState ()=>nav_Screen(userOrigin: userOrigin, userGoal: userGoal);
}
class geostracking
{
Future<Position> determineLocation() async {
bool serviceEnabled;
LocationPermission permission;
serviceEnabled = await Geolocator.isLocationServiceEnabled();
if (!serviceEnabled) {
return Future.error('Location Service are Disabled');
}
permission = await Geolocator.checkPermission();
if (permission == LocationPermission.denied) {
permission = await Geolocator.requestPermission();
if (permission == LocationPermission.denied) {
return Future.error('Location Permission Denied');
}
}
if (permission == LocationPermission.deniedForever) {
return Future.error('Permission Denied Forever');
}
Position position = await Geolocator.getCurrentPosition();
print(position);
return position;
}
Position? listenToLocation()
{
Position? userposition;
final LocationSettings _locationSettings = LocationSettings(accuracy: LocationAccuracy.high,distanceFilter: 100);
userStreamlocation = Geolocator.getPositionStream(locationSettings: _locationSettings).listen(
(userposition) {
print(userposition == null ? 'Unknown' : '${userposition.latitude.toString()}, ${userposition.longitude.toString()}');
setState(){
streamResult=userposition;
}
});
return userposition;
}
}
class nav_Screen extends State<navScreen>
{
StreamSubscription<Position>? streamPosition;
#override
void dispose()
{
super.dispose();
streamPosition?.cancel();
}
late GoogleMapController mapController;
final String userOrigin;
final String userGoal;
nav_Screen({required this.userOrigin,required this.userGoal, });
final LatLng _kGooglePlex = LatLng(baseLat, baseLong);
Set<Marker> _markers = Set<Marker>();
Set<Polyline> _navPolylines =Set<Polyline>();
int _polylineIdCounter=0;
int markerNumber=1;
int _markerIDCounter = 1;
void _setMarker(String ID, var Place) {
String markerLabel;
if(markerNumber==1)
{
markerLabel = 'Start';
}
else
{
markerLabel = "Destination";
}
setState(() {
_markers.addLabelMarker(LabelMarker(
backgroundColor: Color.fromARGB(255, 0, 8, 255),
label: markerLabel,
markerId: MarkerId(ID),
position: LatLng(Place['geometry']['location']['lat'],
Place['geometry']['location']['lng']),)
);
_markerIDCounter++;
markerNumber++;
});
}
void _setPolylines(List<PointLatLng> points) {
final String _navPolylinesID = 'polyline_$_polylineIdCounter';
//print('Check : '+points.toString());
_navPolylines.add(
Polyline(
polylineId: PolylineId(_navPolylinesID),
width: 5,
color: Color.fromARGB(255, 56, 12, 255),
startCap: Cap.roundCap,
endCap: Cap.buttCap,
visible: true,
points: points
.map((point) => LatLng(point.latitude, point.longitude)).toList(),
)
);_polylineIdCounter++;
}
void _onMapCreated(GoogleMapController controller) async {
mapController = controller;
var direction = await LocationService().getDirectionNoWP(userOrigin, userGoal);
print(_polylineIdCounter);
_setPolylines(direction['polyline_decoded']);
String OplaceID = await LocationService().getPlaceID(userOrigin);
var Oplace = await LocationService().getPlace(userOrigin);
_setMarker(OplaceID, Oplace);
String DplaceID = await LocationService().getPlaceID(userGoal);
var Dplace = await LocationService().getPlace(userGoal);
_setMarker(DplaceID, Dplace);
setState(() {});
}
#override
Widget build(BuildContext context)
{
return Scaffold(
appBar: AppBar(title: Text('Test')),
body: Column
(children: [
Expanded(
child:
GoogleMap(
mapType: MapType.normal,
initialCameraPosition: CameraPosition(target: _kGooglePlex,zoom: 10),
markers: _markers,
polylines: _navPolylines,
onMapCreated: _onMapCreated,
)
),
]),
floatingActionButton: Container(alignment: Alignment.bottomCenter,
child: FloatingActionButton(onPressed: ()async{
geostracking().listenToLocation();
},
child: Icon(Icons.navigation),),
),
);
}
}
Here's a snip of the main page code and it's packages
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';
import 'package:google_maps_in_flutter/current_location.dart';
import 'package:google_maps_in_flutter/customer_profile.dart';
import 'package:google_maps_in_flutter/location_service.dart';
import 'package:flutter_polyline_points/flutter_polyline_points.dart';
import 'package:geolocator/geolocator.dart';
import 'package:label_marker/label_marker.dart';
void main() => runApp(MyApp());
StreamSubscription<Position>? userStreamlocation;
Position? streamResult;
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Google Map Test',
home: GMap(),
//routes: ,
);
}
}
class GMap extends StatefulWidget {
#override
State<GMap> createState() => GMapState();
}
class requestTemplateConverter{
class GMapState extends State<GMap> {
Related
I am running into a "type 'Null' is not a subtype of type 'String' in type cast" when I try to retrieve the data.
not sure what the issue is... I think the data is not being found or something along those lines
source code:: https://github.com/casas1010/flutter_firebase_vendor_management
error message::
════════ Exception caught by widgets library ═══════════════════════════════════
The following _CastError was thrown building JobApplicationsListView(dirty):
type 'Null' is not a subtype of type 'String' in type cast
The relevant error-causing widget was
JobApplicationsListView
lib/…/job_applications/job_application_view.dart:75
When the exception was thrown, this was the stack
#0 new CloudJobApplication.fromSnapshot
package:ijob_clone_app/…/cloud/cloud_job_application.dart:27
#1 FirebaseCloudStorage.allJobApplications.<anonymous closure>.<anonymous closure>
package:ijob_clone_app/…/cloud/firebase_cloud_storage.dart:49
#2 MappedListIterable.elementAt (dart:_internal/iterable.dart:413:31)
#3 ListIterator.moveNext (dart:_internal/iterable.dart:342:26)
#4 WhereIterator.moveNext (dart:_internal/iterable.dart:438:22)
#5 Iterable.length (dart:core/iterable.dart:497:15)
#6 JobApplicationsListView.build
package:ijob_clone_app/…/widgets/job_application_list_widget.dart:27
#7 StatelessElement.build
package:flutter/…/widgets/framework.dart:4949
#8 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4878
#9 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#10 ComponentElement._firstBuild
package:flutter/…/widgets/framework.dart:4859
#11 ComponentElement.mount
package:flutter/…/widgets/framework.dart:4853
#12 Element.inflateWidget
package:flutter/…/widgets/framework.dart:3863
#13 Element.updateChild
package:flutter/…/widgets/framework.dart:3586
#14 ComponentElement.performRebuild
package:flutter/…/widgets/framework.dart:4904
#15 StatefulElement.performRebuild
package:flutter/…/widgets/framework.dart:5050
#16 Element.rebuild
package:flutter/…/widgets/framework.dart:4604
#17 BuildOwner.buildScope
package:flutter/…/widgets/framework.dart:2667
#18 WidgetsBinding.drawFrame
package:flutter/…/widgets/binding.dart:882
#19 RendererBinding._handlePersistentFrameCallback
package:flutter/…/rendering/binding.dart:378
#20 SchedulerBinding._invokeFrameCallback
package:flutter/…/scheduler/binding.dart:1175
#21 SchedulerBinding.handleDrawFrame
package:flutter/…/scheduler/binding.dart:1104
#22 SchedulerBinding._handleDrawFrame
package:flutter/…/scheduler/binding.dart:1015
#23 _invoke (dart:ui/hooks.dart:148:13)
#24 PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:318:5)
#25 _drawFrame (dart:ui/hooks.dart:115:31)
════════════════════════════════════════════════════════════════════════════════
D/TrafficStats( 9769): tagSocket(99) with statsTag=0xffffffff, statsUid=-1
CloudJobApplication::
#immutable
class CloudJobApplication {
final String documentId;
final String jobApplicatorId;
final String jobApplicationState;
final String jobApplicationSubState;
const CloudJobApplication({
required this.documentId,
required this.jobApplicatorId,
required this.jobApplicationState,
required this.jobApplicationSubState,
});
// acts as constructor
CloudJobApplication.fromSnapshot(
QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] as String,
jobApplicationState =
snapshot.data()[jobApplicationStateColumn] as String,
jobApplicationSubState =
snapshot.data()[jobApplicationSubStateColumn] as String;
}
FirebaseCloudStorage::
class FirebaseCloudStorage {
final job = FirebaseFirestore.instance.collection('jobs');
final jobApplication =
FirebaseFirestore.instance.collection('job applications');
// This works perfect for getting the jobs
Stream<Iterable<CloudJob>> allJobs({required String jobCreatorId}) =>
job.snapshots().map((event) => event.docs
.map((doc) => CloudJob.fromSnapshot(doc))
.where((job) => job.jobCreatorId == jobCreatorId));
// this does not work. i copied the code from above and changed it
Stream<Iterable<CloudJobApplication>> allJobApplications() =>
jobApplication.snapshots().map((event) => event.docs
.map((doc) => CloudJobApplication.fromSnapshot(doc))
.where((jobApplication) =>
jobApplication.documentId == 'f2FvzZmr51v1wyrYZYoM'));
// singleton
static final FirebaseCloudStorage _shared =
FirebaseCloudStorage._sharedInstance();
FirebaseCloudStorage._sharedInstance();
factory FirebaseCloudStorage() => _shared;
}
JobApplicationsView:: ( this is where the issue starts, the issue appears when this widget tries to retrieve the data from the server i thin )
import 'package:flutter/material.dart';
import '../../services/cloud/cloud_job_application.dart';
import '../../utilities/widgets/job_application_list_widget.dart';
import '../../utilities/widgets/jobs_list_widget.dart';
import '/constants/routes.dart';
import '/enums/menu_action.dart';
import '/services/auth/auth_service.dart';
import '/services/cloud/cloud_job.dart';
import '/services/cloud/firebase_cloud_storage.dart';
import '/utilities/dialogs/logout_dialog.dart';
class JobApplicationsView extends StatefulWidget {
const JobApplicationsView({Key? key}) : super(key: key);
#override
_JobApplicationsViewState createState() => _JobApplicationsViewState();
}
class _JobApplicationsViewState extends State<JobApplicationsView> {
late final FirebaseCloudStorage _jobsService;
String get userId => AuthService.firebase().currentUser!.id;
#override
void initState() {
_jobsService = FirebaseCloudStorage();
super.initState();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Your job applications'),
actions: [
IconButton(
onPressed: () {
// Navigator.of(context).pushNamed(createOrUpdateJobRoute);
},
icon: const Icon(Icons.add),
),
PopupMenuButton<MenuAction>(
onSelected: (value) async {
prin('code removed')
},
itemBuilder: (context) {
return const [
PopupMenuItem<MenuAction>(
value: MenuAction.logout,
child: Text('Log out'),
),
];
},
)
],
),
body: StreamBuilder(
stream: _jobsService.allJobApplications(),
builder: (context, snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.waiting:
case ConnectionState.active:
if (snapshot.hasData) {
final allJobs = snapshot.data as Iterable<CloudJobApplication>;
print(snapshot);
return JobApplicationsListView( // ERROR IS OCURRING HERE
jobs: allJobs,
);
return Text('results');
} else {
return const CircularProgressIndicator();
}
default:
return const CircularProgressIndicator();
}
},
),
);
}
}
Try like this
CloudJobApplication.fromSnapshot(
QueryDocumentSnapshot<Map<String, dynamic>> snapshot)
: documentId = snapshot.id,
jobApplicatorId = snapshot.data()[jobApplicatorIdColumn] ?? "",
jobApplicationState = snapshot.get(jobApplicationStateColumn) ?? "",
jobApplicationSubState =
snapshot.get(jobApplicationSubStateColumn) ?? "";
Well the problem I am having here, normally if I wrap materialApp with global overlay support, it should be working, but it is not as you can see from debug console. Any suggestions? I am normally trying integrate firebase on iOS. The restart app is causing problem I guess, but I do not want to throw it out, to saying truth
// ignore_for_file: prefer_const_constructors, duplicate_ignore
import 'package:firebase_messaging/firebase_messaging.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:medicte/pages/home_page.dart';
import 'package:animated_splash_screen/animated_splash_screen.dart';
import 'package:overlay_support/overlay_support.dart';
import 'package:page_transition/page_transition.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:firebase_core/firebase_core.dart';
import 'firebase_options.dart';
Future _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
if (kDebugMode) {
print("Handling a background message: ${message.messageId}");
}
}
main() {
runApp(RestartWidget(child: MyApp()));
}
Future<void> initializeDefault() async {
FirebaseApp app = await Firebase.initializeApp(
options: DefaultFirebaseOptions.currentPlatform,
);
if (kDebugMode) {
print('Initialized default app $app');
}
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
// ignore: prefer_const_constructors
return ScreenUtilInit(
designSize: const Size(428, 926),
builder: (context, child) => OverlaySupport.global(
child: MaterialApp(
debugShowCheckedModeBanner: false,
home: SplashScreen(),
),
),
);
}
}
class RestartWidget extends StatefulWidget {
const RestartWidget({Key? key, required this.child}) : super(key: key);
final Widget child;
static void restartApp(BuildContext context) {
context.findAncestorStateOfType<_RestartWidgetState>()?.restartApp();
}
#override
// ignore: library_private_types_in_public_api
_RestartWidgetState createState() => _RestartWidgetState();
}
class _RestartWidgetState extends State<RestartWidget> {
late final FirebaseMessaging _messaging;
PushNotification? _notificationInfo;
void requestAndRegisterNotification() async {
// 1. Initialize the Firebase app
await initializeDefault();
// 2. Instantiate Firebase Messaging
_messaging = FirebaseMessaging.instance;
FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
// 3. On iOS, this helps to take the user permissions
NotificationSettings settings = await _messaging.requestPermission(
alert: true,
badge: true,
provisional: false,
sound: true,
);
if (settings.authorizationStatus == AuthorizationStatus.authorized) {
if (kDebugMode) {
print('User granted permission');
}
String? token = await _messaging.getToken();
if (kDebugMode) {
print("The token is ${token!}");
}
// For handling the received notifications
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
// Parse the message received
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
if (kDebugMode) {
print("The notification is $notification");
}
setState(() {
_notificationInfo = notification;
});
if (_notificationInfo != null) {
// For displaying the notification as an overlay
showSimpleNotification(
Text(_notificationInfo!.title!),
subtitle: Text(_notificationInfo!.body!),
background: Colors.cyan.shade700,
duration: Duration(seconds: 2),
);
}
});
} else {
if (kDebugMode) {
print('User declined or has not accepted permission');
}
}
}
#override
void initState() {
requestAndRegisterNotification();
FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
PushNotification notification = PushNotification(
title: message.notification?.title,
body: message.notification?.body,
);
setState(() {
_notificationInfo = notification;
});
});
super.initState();
}
Key key = UniqueKey();
void restartApp() {
setState(() {
key = UniqueKey();
});
}
#override
Widget build(BuildContext context) {
return KeyedSubtree(
key: key,
child: widget.child,
);
}
}
class SplashScreen extends StatelessWidget {
const SplashScreen({Key? key}) : super(key: key);
#override
Widget build(BuildContext context) {
return AnimatedSplashScreen(
splash: Image.asset(
'lib/images/MedicteLogo-4a2e31cd2358bb08ff8d12acb2761357.png'),
nextScreen: HomePage(),
splashTransition: SplashTransition.scaleTransition,
pageTransitionType: PageTransitionType.rightToLeftWithFade,
);
}
}
class PushNotification {
PushNotification({
this.title,
this.body,
});
String? title;
String? body;
}
Heading
This is my debug console:
>2022-09-02 12:02:26.023971+0300 Runner[19573:866637] Metal API Validation Enabled
2022-09-02 12:02:26.194783+0300 Runner[19573:866637] Could not load the "LaunchImage" image referenced from a nib in the bundle with identifier "com.example.medicte"
2022-09-02 12:02:26.208267+0300 Runner[19573:866829] 9.4.0 - [FirebaseCore][I-COR000012] Could not locate configuration file: 'GoogleService-Info.plist'.
2022-09-02 12:02:26.236111+0300 Runner[19573:866823] 9.4.0 - [FirebaseCore][I-COR000003] The default Firebase app has not yet been configured. Add `FirebaseApp.configure()` to your application initialization. This can be done in in the App Delegate's application(_:didFinishLaunchingWithOptions:)` (or the `#main` struct's initializer in SwiftUI). Read more: https:/goo.gl/ctyzm8.
2022-09-02 12:02:26.237231+0300 Runner[19573:866823] 9.4.0 - [FirebaseCore][I-COR000003] The default Firebase app has not yet been configured. Add `FirebaseApp.configure()` to your application initialization. This can be done in in the App Delegate's application(_:didFinishLaunchingWithOptions:)` (or the `#main` struct's initializer in SwiftUI). Read more: https:/goo.gl/ctyzm8.
2022-09-02 12:02:26.279437+0300 Runner[19573:866849] flutter: The Dart VM service is listening on http://127.0.0.1:51958/HXJzT6ZmSJY=/
2022-09-02 12:02:26.614633+0300 Runner[19573:866825] 9.4.0 - [FirebaseCore][I-COR000005] No app has been configured yet.
2022-09-02 12:02:26.836889+0300 Runner[19573:866830] 9.4.0 - [FirebaseCore][I-COR000005] No app has been configured yet.
2022-09-02 12:02:26.912218+0300 Runner[19573:866823] 9.4.0 - [FirebaseMessaging][I-FCM001000] FIRMessaging Remote Notifications proxy enabled, will swizzle remote notification receiver handlers. If you'd prefer to manually integrate Firebase Messaging, add "FirebaseAppDelegateProxyEnabled" to your Info.plist, and set it to NO. Follow the instructions at:
https://firebase.google.com/docs/cloud-messaging/ios/client#method_swizzling_in_firebase_messaging
to ensure proper integration.
2022-09-02 12:02:26.922498+0300 Runner[19573:866833] flutter: Initialized default app FirebaseApp([DEFAULT])
2022-09-02 12:02:26.922884+0300 Runner[19573:866823] 9.4.0 - [FirebaseMessaging][I-FCM002022] APNS device token not set before retrieving FCM Token for Sender ID '204532241696'. Notifications to this FCM Token will not be delivered over APNS.Be sure to re-retrieve the FCM token once the APNS device token is set.
2022-09-02 12:02:27.019553+0300 Runner[19573:866833] flutter: User granted permission
2022-09-02 12:02:29.000587+0300 Runner[19573:866833] flutter: The token is c1P2bEEh9Et3njcfkiOntp:APA91bFZIAR4oxrrwi0aJuYVofPC93x6wjy39TCTUt8-w6PkxtDgKTQUv-iQamhnd_pox6q2mm4JvBD6hSBS3bWmbzp8BO0LhpR89PvMwJv5ZdPWokguVkpMW6t5YUdIfVPwhlfTpsY5
2022-09-02 12:02:38.677058+0300 Runner[19573:866833] flutter: The notification is Instance of 'PushNotification'
2022-09-02 12:02:38.681029+0300 Runner[19573:866833] [VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: 'package:overlay_support/src/overlay_state_finder.dart': Failed assertion: line 12 pos 7: '_debugInitialized': Global OverlaySupport Not Initialized !
ensure your app wrapped widget OverlaySupport.global
#0 _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:51:61)
#1 _AssertionError._throwNew (dart:core-patch/errors_patch.dart:40:5)
#2 findOverlayState (package:overlay_support/src/overlay_state_finder.dart:12:7)
#3 showOverlay (package:overlay_support/src/overlay.dart:63:26)
#4 showOverlayNotification (package:overlay_support/src/notification/overlay_notification.dart:21:10)
#5 showSimpleNotification (package:overlay_support/src/notification/overlay_notification.dart:97:17)
#6 _RestartWidgetState.requestAndRegisterNotification.<anonymous closure> (package:medicte/main.dart:106:11)
#7 _rootRunUnary (dart:async/zone.dart:1434:47)
#8 _CustomZone.runUnary (dart:async/zone.dart:1335:19)
#9 _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
#10 _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
#11 _DelayedData.perform (dart:async/stream_impl.dart:591:14)
#12 _StreamImplEvents.handleNext (dart:async/stream_impl.dart:706:11)
#13 _PendingEvents.schedule.<anonymous closure> (dart:async/stream_impl.dart:663:7)
#14 _rootRun (dart:async/zone.dart:1418:47)
#15 _CustomZone.run (dart:async/zone.dart:1328:19)
#16 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#17 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
#18 _rootRun (dart:async/zone.dart:1426:13)
#19 _CustomZone.run (dart:async/zone.dart:1328:19)
#20 _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
#21 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
#22 _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
#23 _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
Actually, error is Could not locate configuration file: 'GoogleService-Info.plist'.
If you didn't initialize the Firebase project, start with and follow this doc
firebase init
After all done, you will find
keep getting "Null check operator used on a null value" error
actually im trying to use providers to get values from database and use em in my app
but im stuck at this i checked my code in every single way but still i keep getting this error
:lib\providers\user_provider.dart
import 'package:flutter/widgets.dart';
import 'package:test_app/models/user.dart';
import 'package:test_app/resources/auth_methods.dart';
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User get getUser => _user!;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
lib\pages\home.dart
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'package:test_app/providers/user_provider.dart';
import 'package:test_app/models/user.dart' as model;
// import 'dart:html';
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
State<Home> createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
#override
Widget build(BuildContext context) {
model.User user = Provider.of<UserProvider>(context).getUser;
return Scaffold(
body: Center(
child: Text("this is homepage"),
),
);
}
}
debug snippet
══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
The following _CastError was thrown building Home(dirty, dependencies:
[_InheritedProviderScope<UserProvider?>], state: _HomeState#17895):
Null check operator used on a null value
The relevant error-causing widget was:
Home Home:file:///C:/Users/abc/Desktop/flutter/test_app/lib/main.dart:53:34
When the exception was thrown, this was the stack:
#0 UserProvider.getUser (package:test_app/providers/user_provider.dart:9:28)
#1 _HomeState.build (package:test_app/pages/home.dart:36:59)
#2 StatefulElement.build (package:flutter/src/widgets/framework.dart:4870:27)
#3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4754:15)
#4 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#5 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#6 ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:4735:5)
#7 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4919:11)
#8 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4729:5)
#9 Element.inflateWidget (package:flutter/src/widgets/framework.dart:3790:14)
#10 Element.updateChild (package:flutter/src/widgets/framework.dart:3524:20)
#11 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4780:16)
#12 StatefulElement.performRebuild (package:flutter/src/widgets/framework.dart:4928:11)
#13 Element.rebuild (package:flutter/src/widgets/framework.dart:4477:5)
#14 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2659:19)
#15 WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:882:21)
#16 RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:363:5)
#17 SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1144:15)
#18 SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1081:9)
#19 SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:862:7)
(elided 11 frames from class _RawReceivePortImpl, class _Timer, dart:async, and dart:async-patch)
idk what the problem actually im new to flutter and dart
i've using python for my whole life
refreshUser is a future and it sets _user but because you're calling getUser IMMEDIATELY build method, which basically returns _user as a non-null value, the error would be thrown.
Try this:
class UserProvider with ChangeNotifier {
User? _user;
final AuthMethods _authMethods = AuthMethods();
User? get getUser => _user;
Future<void> refreshUser() async {
User user = await _authMethods.getUserDetails();
_user = user;
notifyListeners();
}
}
And your _HomeState:
class _HomeState extends State<Home> {
#override
void initState() {
super.initState();
addData();
}
addData() async {
UserProvider _userProvider =
Provider.of<UserProvider>(context, listen: false);
await _userProvider.refreshUser();
}
#override
Widget build(BuildContext context) {
model.User? user = Provider.of<UserProvider>(context).getUser;
return Scaffold(
body: Center(
child: Text("this is homepage"),
),
);
}
}
In User_Provider.dart,
instead of doing:
User get getUser => _user!;
Do this:
User? get getUser => _user;
I'm writing unit tests for my Flutter app and I'm having some trouble when reading a json file. I have some json files that are used by my api mock class. Whenever I call a method on the File object, it never ends, but the test continues to execute, ending in an error because it didn't receive the data from the file object. It's very weird because it only happens when the mock api method is called from a provider that is called from a widget. If I call the mock api method directly my test, it works fine.
The structure of my app is as follows: WidgetScreen calls -> provider calls -> mockApi.
The Widget LegislacaoScreen calls the method carregarLegislacao from my provider, that in turn calls the method getLegislacoes from my mockApi, that method reads from a json file and returns the results to the provider that then notifies my widget. Any help is appreciated.
Oh and I'm running my tests with the command: flutter test test/my_test.dart
Here some code:
LegislacaoScreen:
class LegislacaoScreen extends StatefulWidget {
#override
_LegislacaoScreenState createState() => _LegislacaoScreenState();
}
class _LegislacaoScreenState extends State<LegislacaoScreen>
with AutomaticKeepAliveClientMixin {
#override
void initState() {
super.initState();
Future.microtask(carregarDados);
}
#override
bool get wantKeepAlive => true;
Future<void> carregarDados({bool reset = false}) async {
try {
final legislacaoProvider =
Provider.of<LegislacaoProvider>(context, listen: false);
await legislacaoProvider.carregarLegislacao(
page: legislacaoProvider.currentPage + 1,
reset: reset,
);
} catch (err) {}
}
Widget renderBody(legislacaoProvider) {
if (legislacaoProvider.carregandoLegislacao &&
legislacaoProvider.legislacoes.isEmpty &&
!legislacaoProvider.reseting) {
return Center(
child: CircularProgressIndicator(),
);
}
if (legislacaoProvider.erroCarregandoLegislacao) {
return MensagemAcao(
mensagem:
'Houve um erro ao carregar os dados.\nPor favor tente novamente.',
acao: () => carregarDados(reset: true),
);
}
return LegislacaoLista(
carregandoLegislacao: legislacaoProvider.carregandoLegislacao,
legislacoes: legislacaoProvider.legislacoes,
reseting: legislacaoProvider.reseting,
carregarDados: carregarDados,
isFiltroEmpty: legislacaoProvider.isFiltroEmpty,
);
}
#override
Widget build(BuildContext context) {
super.build(context);
final legislacaoProvider = Provider.of<LegislacaoProvider>(context);
return Scaffold(
appBar: CustomAppBar(
title: 'Legislação',
actions: <Widget>[
IconButton(
icon: Icon(
Icons.search,
color: legislacaoProvider.isFiltroEmpty
? Colors.white
: CustomColors.verde2,
),
onPressed: () {
Navigator.of(context)
.pushNamed(PesquisarLegislacaoScreen.routeName);
},
),
],
),
backgroundColor: Colors.white,
body: renderBody(legislacaoProvider),
);
}
Provider:
class LegislacaoProvider with ChangeNotifier {
bool _carregandoLegislacao = true;
bool _erroCarregandoLegislacao = false;
List<Legislacao> legislacoes = [];
int currentPage = 0;
bool _reseting = false;
LegislacaoApi _legislacaoApi;
LegislacaoProvider({LegislacaoApi legislacaoApi})
: _legislacaoApi = legislacaoApi ?? LegislacaoApiService();
bool get carregandoLegislacao {
return _carregandoLegislacao;
}
bool get erroCarregandoLegislacao {
return _erroCarregandoLegislacao;
}
bool get reseting {
return _reseting;
}
Future<void> carregarLegislacao({
int page = 1,
bool reset = false,
}) async {
try {
_carregandoLegislacao = true;
_erroCarregandoLegislacao = false;
_reseting = reset;
if (reset) {
page = 1;
}
notifyListeners();
legislacoes = await _legislacaoApi.getLegislacoes(
page: page,
ementa: filtro['ementa'],
conteudo: filtro['conteudo'],
ano: filtro['ano'],
periodoInicialLegislacao: filtro['periodoInicialLegislacao'],
periodoFinalLegislacao: filtro['periodoFinalLegislacao'],
tipoLegislacao: filtro['tipoLegislacao']?.id,
numero: filtro['numero'],
autor: filtro['autor'],
);
_carregandoLegislacao = false;
_reseting = false;
notifyListeners();
} catch (err) {
print(err);
_erroCarregandoLegislacao = true;
_carregandoLegislacao = false;
_reseting = false;
notifyListeners();
throw TaNaLeiException(err.toString());
}
}
}
MockApi:
class LegislacaoApiServiceMock extends LegislacaoApi {
bool _fail = false;
LegislacaoApiServiceMock();
LegislacaoApiServiceMock.fail() : _fail = true;
#override
Future<List<Legislacao>> getLegislacoes({
int page = 1,
String conteudo,
String ementa,
String ano,
DateTime periodoInicialLegislacao,
DateTime periodoFinalLegislacao,
int tipoLegislacao,
String numero,
String autor,
}) async {
if (_fail) {
throw Error();
}
final file = File('test/data/get_legislacoes.json');
print('step 1');
final json = await file.readAsString();
print('step 2 '); // <-- NEVER GETS PRINTED
return jsonDecode(json)
.map<Legislacao>(
(elemento) => Legislacao.fromJson(elemento),
)
.toList();
}
}
And finally, my tests:
final locator = GetIt.instance;
void setupLocatorLegislacaoProvider({LegislacaoApi legislacaoApi}) {
locator.registerLazySingleton<LegislacaoProvider>(() => LegislacaoProvider(
legislacaoApi: legislacaoApi,
));
}
void main() async {
TestWidgetsFlutterBinding.ensureInitialized();
setupLocatorLegislacaoProvider(legislacaoApi: LegislacaoApiServiceMock());
group('LegislacaoScreen', () {
Widget buildWidget() {
return ChangeNotifierProvider.value(
value: locator<LegislacaoProvider>();,
child: MaterialApp(
home: LegislacaoScreen(),
routes: routes,
),
);
}
testWidgets('builds screen', (WidgetTester tester) async {
final child = buildWidget();
await tester.pumpWidget(child);
expect(find.byWidget(child), findsOneWidget);
});
testWidgets('finds list when data is loaded',
(WidgetTester tester) async {
await tester.pumpWidget(buildWidget());
await tester.pump();
await tester.pump();
expect(find.byType(LegislacaoLista), findsOneWidget);
});
});
}
EDIT:
Here is the error message from running the tests:
➜ ta_na_lei git:(testes) ✗ flutter test test/ui/screens/legislacao/legislacao_screen_test.dart
00:03 +0: LegislacaoScreen builds screen
dentro de mock 1
00:04 +1: LegislacaoScreen exibe circular progress indicator quando carregando legislacao e reset true
dentro de mock 1
00:04 +2: LegislacaoScreen exibe lista de legislacao quando legislacoes carregadas
dentro de mock 1
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following TestFailure object was thrown running a test:
Expected: exactly one matching node in the widget tree
Actual: _WidgetTypeFinder:<zero widgets with type "LegislacaoLista" (ignoring offstage widgets)>
Which: means none were found but one was expected
When the exception was thrown, this was the stack:
#4 main.<anonymous closure>.<anonymous closure> (file:///Users/home/Projetos/casacivil/ta_na_lei/test/ui/screens/legislacao/legislacao_screen_test.dart:49:7)
<asynchronous suspension>
#5 main.<anonymous closure>.<anonymous closure> (file:///Users/home/Projetos/casacivil/ta_na_lei/test/ui/screens/legislacao/legislacao_screen_test.dart)
#6 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:140:29)
<asynchronous suspension>
#7 testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart)
#8 TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:703:19)
<asynchronous suspension>
#11 TestWidgetsFlutterBinding._runTest (package:flutter_test/src/binding.dart:683:14)
#12 AutomatedTestWidgetsFlutterBinding.runTest.<anonymous closure> (package:flutter_test/src/binding.dart:1083:24)
#18 AutomatedTestWidgetsFlutterBinding.runTest (package:flutter_test/src/binding.dart:1080:15)
#19 testWidgets.<anonymous closure> (package:flutter_test/src/widget_tester.dart:133:24)
#20 Declarer.test.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:172:27)
<asynchronous suspension>
#21 Declarer.test.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart)
#22 Invoker.waitForOutstandingCallbacks.<anonymous closure> (package:test_api/src/backend/invoker.dart:246:15)
#27 Invoker.waitForOutstandingCallbacks (package:test_api/src/backend/invoker.dart:243:5)
#28 Declarer.test.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/declarer.dart:170:33)
#33 Declarer.test.<anonymous closure> (package:test_api/src/backend/declarer.dart:169:13)
#34 Invoker._onRun.<anonymous closure>.<anonymous closure>.<anonymous closure>.<anonymous closure> (package:test_api/src/backend/invoker.dart:400:30)
(elided 31 frames from class _FakeAsync, class _RawReceivePortImpl, class _Timer, dart:async, dart:async-patch, and package:stack_trace)
This was caught by the test expectation on the following line:
file:///Users/home/Projetos/casacivil/ta_na_lei/test/ui/screens/legislacao/legislacao_screen_test.dart line 49
The test description was:
exibe lista de legislacao quando legislacoes carregadas
════════════════════════════════════════════════════════════════════════════════════════════════════
00:04 +2 -1: LegislacaoScreen exibe lista de legislacao quando legislacoes carregadas [E]
Test failed. See exception logs above.
The test description was: exibe lista de legislacao quando legislacoes carregadas
00:04 +3 -1: Some tests failed.
EDIT 2:
It seems the issue is with the async environment, after I read this article https://medium.com/flutter/event-loop-in-widget-tester-50b3ca5e9fc5 . I tried to call my test inside a runAsync method, it did not work, then I added await Future.delayed(Duration(seconds: 5)) and It worked. For some reason its taking a long time to read the file (In other tests it reads really fast). One interesting thing is that pump with a duration does not delay the tests...
Well, it works now with this workaround, but I'd like to know the correct way to fix the issue.
await tester.runAsync(() async {
await tester.pumpWidget(buildWidget());
await Future.delayed(Duration(seconds: 5));
await tester.pump(Duration(seconds: 2));
expect(find.byType(LegislacaoLista), findsOneWidget);
});
I'm trying to make possible the following actions:
I run my app and when I press the "Connect" button I connect to my BLE module.
A second button allows me to disconnect from it.
The problem is that if I connect to the BLE module, and then press the disconnect button, it disconnect but I will no longer be able to connect to the BLE anymore (and I have to restart the app).
There is my code:
import 'dart:async';
import 'dart:convert' show utf8;
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_blue/flutter_blue.dart';
void main() {
SystemChrome.setPreferredOrientations([
DeviceOrientation.landscapeRight,
DeviceOrientation.landscapeLeft
]);
runApp(MainScreen());
}
class MainScreen extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BLUETOOTH',
debugShowCheckedModeBanner: false,
home: Home(),
theme: ThemeData.dark(),
);
}
}
class Home extends StatefulWidget {
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
String connectionText = "";
final String SERVICE_UUID = "4fafc201-1fb5-459e-8fcc-c5c9c331914b";
final String CHARACTERISTIC_UUID = "beb5483e-36e1-4688-b7f5-ea07361b26a8";
final String TARGET_DEVICE_NAME = "MLT-BT05";
FlutterBlue flutterBlue = FlutterBlue.instance; // * Instance de FlutterBlue
StreamSubscription<ScanResult> scanSubScription; // * StreamSubscription
BluetoothDevice targetDevice; // * Device
BluetoothCharacteristic targetCharacteristic; // * Characteristiques
#override
void initState() {
super.initState();
// startScan();
}
startScan() {
setState(() {
connectionText = "Start Scanning";
});
scanSubScription = flutterBlue.scan().listen((scanResult) {
print(scanResult.device.name.toString()); // ! TEST
if (scanResult.device.name == TARGET_DEVICE_NAME) {
print('DEVICE found');
stopScan();
setState(() {
connectionText = "Found Target Device";
});
targetDevice = scanResult.device;
connectToDevice();
}
}, onDone: () => stopScan());
}
stopScan() {
scanSubScription?.cancel();
scanSubScription = null;
}
connectToDevice() async {
if (targetDevice == null) return;
setState(() {
connectionText = "Device Connecting";
});
await targetDevice.connect();
print('DEVICE CONNECTED');
setState(() {
connectionText = "Device Connected";
});
discoverServices();
}
disconnectFromDevice() {
if (targetDevice == null) return;
targetDevice.disconnect();
setState(() {
connectionText = "Device Disconnected";
});
}
discoverServices() async {
if (targetDevice == null) return;
List<BluetoothService> services = await targetDevice.discoverServices();
services.forEach((service) {
// do something with service
if (service.uuid.toString() == SERVICE_UUID) {
service.characteristics.forEach((characteristic) {
if (characteristic.uuid.toString() == CHARACTERISTIC_UUID) {
targetCharacteristic = characteristic;
writeData("Hi there, ESP32!!");
setState(() {
connectionText = "All Ready with ${targetDevice.name}";
});
}
});
}
});
}
writeData(String data) {
if (targetCharacteristic == null) return;
List<int> bytes = utf8.encode(data);
targetCharacteristic.write(bytes);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(connectionText),
centerTitle: true,
),
body: Center(
child: Column(
children: <Widget>[
FlatButton(
child: Text("Connect"),
color: Colors.grey[700],
onPressed: () {
startScan();
},
),
FlatButton(
child: Text("Disconnect"),
color: Colors.grey[700],
onPressed: () {
disconnectFromDevice();
},
),
],
),
),
);
}
}
The error tells me that another scan is already in progress even though the scanSubScription is canceled and set to null once the device is connected.
The error:
I/flutter (13433): [TV] Samsung 7 Series (55)
I/flutter (13433): MLT-BT05
I/flutter (13433): DEVICE found
I/flutter (13433): DEVICE CONNECTED
E/flutter (13433): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: Exception: Another scan is already in progress.
E/flutter (13433): #0 FlutterBlue.scan (package:flutter_blue/src/flutter_blue.dart:81:7)
E/flutter (13433): <asynchronous suspension>
E/flutter (13433): #1 _HomeState.startScan (package:bluetoothv8/main.dart:53:36)
E/flutter (13433): #2 _HomeState.build.<anonymous closure> (package:bluetoothv8/main.dart:140:17)
E/flutter (13433): #3 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:706:14)
E/flutter (13433): #4 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:789:36)
E/flutter (13433): #5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (13433): #6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:486:11)
E/flutter (13433): #7 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:264:5)
E/flutter (13433): #8 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:199:7)
E/flutter (13433): #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:467:9)
E/flutter (13433): #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (13433): #11 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:117:9)
E/flutter (13433): #12 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (13433): #13 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:115:18)
E/flutter (13433): #14 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:7)
E/flutter (13433): #15 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (13433): #16 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (13433): #17 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (13433): #18 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (13433): #19 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (13433): #20 _rootRunUnary (dart:async/zone.dart:1138:13)
E/flutter (13433): #21 _CustomZone.runUnary (dart:async/zone.dart:1031:19)
E/flutter (13433): #22 _CustomZone.runUnaryGuarded (dart:async/zone.dart:933:7)
E/flutter (13433): #23 _invoke1 (dart:ui/hooks.dart:273:10)
E/flutter (13433): #24 _dispatchPointerDataPacket (dart:ui/hooks.dart:182:5)
Instead of:
stopScan() {
scanSubScription?.cancel();
scanSubScription = null;
}
write:
stopScan() {
flutterBlue.stopScan();
scanSubScription?.cancel();
scanSubScription = null;
}
please use like this
bluetoothInstance.stopScan().then((value) {
scanSubscription.cancel();
scanBLE(); //if you need, you can start scan again
});