I'm trying to access the device microphone on press with the aim of recording a voice-note. I have tried to access the current permission value but get the following error:
[VERBOSE-2:ui_dart_state.cc(166)] Unhandled Exception: MissingPluginException(No implementation found for method checkPermissionStatus on channel flutter.baseflow.com/permissions/methods)
#0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:159:7)
<asynchronous suspension>
#1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
#2 MethodChannelPermissionHandler.checkPermissionStatus (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:15:41)
#3 PermissionActions.status (package:permission_handler/permission_handler.dart:30:51)
#4 _InsideLeftState.build.<anonymous closure> (package:easy_tiger/screens/order_card_flow/insideleft.dart:19:62)
#5 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:184:24)
#6 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:524:11)
#7 BaseTapGestureRecognizer._checkUp (pa<…>
[VERBOSE-2:profiler_metrics_ios.mm(184)] Error retrieving thread information: (ipc/send) invalid destination port
Here is the code for my screen:
import 'package:flutter/material.dart';
import 'package:audio_recorder/audio_recorder.dart';
import 'package:permission_handler/permission_handler.dart';
class InsideLeft extends StatefulWidget {
#override
_InsideLeftState createState() => _InsideLeftState();
}
class _InsideLeftState extends State<InsideLeft> {
#override
Widget build(BuildContext context) {
return Container(
child: GestureDetector(
child: Icon(Icons.mic),
onTap: () async {
PermissionStatus mic = await Permission.microphone.status;
print('microphone permission? ${mic.toString()}');
// try {
//// if (mic != PermissionStatus.granted) {
//// await Permission.microphone.request();
//// }
//// } catch (e) {
//// print(e);
//// }
},
),
);
}
}
Any thoughts how to get around this?
can you please try these things :
Migrate to androidX using android Studio
delete gradle caches
Good post about this topic: Flutter MissingPluginException with several plugins
Related
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
Iam trying to add two permissions i.e. storage and camera. I have done the required setup in androidmanifest.xml file and in the main.dart called both the requests using switch. It gives the error but the app works and the permissions are also updated
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:teamup/Connectivity/network_binding.dart';
import 'package:teamup/Views/Login/sign_in.dart';
import 'package:teamup/Views/OnboardingScreen/onboarding_screen.dart';
import 'Views/OnboardingScreen/onboarding_constants.dart';
void main() async {
await GetStorage.init();
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late Permission cameraPermission;
late Permission storagePermission;
PermissionStatus cameraPermissionStatus = PermissionStatus.denied;
PermissionStatus storagePermissionStatus = PermissionStatus.denied;
void _listenForPermission() async {
final cameraStatus = await Permission.camera.status;
final storageStatus = await Permission.storage.status;
setState(() {
cameraPermissionStatus = cameraStatus;
storagePermissionStatus = storageStatus;
});
switch (cameraStatus) {
case PermissionStatus.denied:
requestForPermission();
break;
case PermissionStatus.granted:
break;
case PermissionStatus.restricted:
Navigator.pop(context);
break;
case PermissionStatus.limited:
Navigator.pop(context);
break;
case PermissionStatus.permanentlyDenied:
Navigator.pop(context);
break;
}
switch (storageStatus) {
case PermissionStatus.denied:
requestForPermission();
break;
case PermissionStatus.granted:
break;
case PermissionStatus.restricted:
Navigator.pop(context);
break;
case PermissionStatus.limited:
Navigator.pop(context);
break;
case PermissionStatus.permanentlyDenied:
Navigator.pop(context);
break;
}
}
Future<void> requestForPermission() async {
final cameraStatus = await Permission.camera.request();
final storageStatus = await Permission.storage.request();
setState(() {
cameraPermissionStatus = cameraStatus;
storagePermissionStatus = storageStatus;
});
}
#override
void initState() {
super.initState();
_listenForPermission();
isViewed.writeIfNull('key', 0);
print(isViewed.read('key'));
}
#override
Widget build(BuildContext context) {
return GetMaterialApp(
debugShowCheckedModeBanner: false,
theme: ThemeData(primarySwatch: Colors.blue, fontFamily: 'Glory'),
initialBinding: NetworkBinding() ,
home: isViewed.read('key') != 0
? const SignInPage()
: const OnboardingPage(),
);
}
}
This is the message that was displayed after installation
Launching lib\main.dart on Redmi Note 4 in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Installing build\app\outputs\flutter-apk\app.apk...
W/FlutterActivityAndFragmentDelegate(21677): A splash screen was provided to Flutter, but this is deprecated. See flutter.dev/go/android-splash-migration for migration steps.
Debug service listening on ws://127.0.0.1:56092/dh3Yn3XCkGg=/ws
Syncing files to device Redmi Note 4...
I/FA (21677): Tag Manager is not found and thus will not be used
I/flutter (21677): 0
[GETX] Instance "GetMaterialController" has been created
[GETX] Instance "GetMaterialController" has been initialized
[GETX] Instance "GetXNetworkManager" has been created
[GETX] Instance "GetXNetworkManager" has been initialized
I/Timeline(21677): Timeline: Activity_launch_request time:267480997 intent:Intent { act=android.content.pm.action.REQUEST_PERMISSIONS pkg=com.google.android.packageinstaller (has extras) }
E/flutter (21677): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: PlatformException(PermissionHandler.PermissionManager, A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)., null, null)
E/flutter (21677): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:607:7)
E/flutter (21677): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #2 MethodChannelPermissionHandler.requestPermissions (package:permission_handler_platform_interface/src/method_channel/method_channel_permission_handler.dart:71:9)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #3 PermissionActions.request (package:permission_handler/permission_handler.dart:44:31)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677): #4 _MyAppState.requestForPermission (package:teamup/main.dart:75:26)
E/flutter (21677): <asynchronous suspension>
E/flutter (21677):
I/Timeline(21677): Timeline: Activity_launch_request time:267501469 intent:Intent { act=android.content.pm.action.REQUEST_PERMISSIONS pkg=com.google.android.packageinstaller (has extras) }
The switch-statements in _listenForPermission will call requestForPermission twice, if both cameraStatus and storageStatus have status PermissionStatus.denied. Therefore you get the exception:
PlatformException(PermissionHandler.PermissionManager, A request for permissions is already running, please wait for it to finish before doing another request (note that you can request multiple permissions at the same time)., null, null)
The permission_handler package allows you to request multiple permission in one call like this:
// You can request multiple permissions at once.
Map<Permission, PermissionStatus> statuses = await [
Permission.location,
Permission.storage,
].request();
print(statuses[Permission.location]);
I want to get the HERE credentials from a web service and not from the android manifest or info.plist as stated in the HERE documentation, but at this point I get an error.
Here Flutter SDK version 4.8.0.0
import 'package:flutter/material.dart';
import 'package:here_sdk/core.dart';
import 'package:here_sdk/core.engine.dart';
import 'package:here_sdk/core.errors.dart';
import 'package:here_sdk/mapview.dart';
void main() {
SDKOptions sdkOptions = SDKOptions.withAccessKeySecretAndCachePath(
"YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET", "");
SDKNativeEngine sdkNativeEngine;
try {
sdkNativeEngine = SDKNativeEngine(sdkOptions);
SDKNativeEngine.sharedInstance = sdkNativeEngine;
} on InstantiationException {
// Handle exception.
}
SdkContext.init(IsolateOrigin.main);
runApp(MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'HERE SDK for Flutter - Hello Map!',
home: HereMap(onMapCreated: _onMapCreated),
);
}
void _onMapCreated(HereMapController hereMapController) {
hereMapController.mapScene.loadSceneForMapScheme(MapScheme.normalDay,
(MapError? error) {
if (error != null) {
print('Map scene not loaded. MapError: ${error.toString()}');
return;
}
const double distanceToEarthInMeters = 8000;
hereMapController.camera.lookAtPointWithDistance(
GeoCoordinates(52.530932, 13.384915), distanceToEarthInMeters);
});
}
}
An error occurred
E/flutter (16773): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Invalid argument(s): Failed to resolve an FFI function. Perhaps `LibraryContext.init()` was not called.
E/flutter (16773): Failed to lookup symbol (undefined symbol: here_sdk_sdk_core_engine_SDKOptions_make__String_String_String)
E/flutter (16773): #0 catchArgumentError (package:here_sdk/src/_library_context.dart:39:5)
E/flutter (16773): #1 SDKOptions._withAccessKeySecretAndCachePath (package:here_sdk/src/sdk/core/engine/s_d_k_options.dart:207:49)
E/flutter (16773): #2 new SDKOptions.withAccessKeySecretAndCachePath (package:here_sdk/src/sdk/core/engine/s_d_k_options.dart:94:121)
E/flutter (16773): #3 main (package:here_example/main.dart:8:38)
E/flutter (16773): #4 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:142:25)
E/flutter (16773): #5 _rootRun (dart:async/zone.dart:1354:13)
How can I implement LibraryContext.init()?
Can you share code snippet about that?
Thanks.
Make sure to init the SDKContext before initializing the HERE SDK. I wish this would have been stated in the documentation, but apparently it is not.
So, instead of calling it after creating the SDKNativeEngine, call it like so:
void main() {
SdkContext.init(IsolateOrigin.main);
// Clear the cache occupied by a previous instance.
await SDKNativeEngine.sharedInstance?.dispose();
SDKOptions sdkOptions = SDKOptions.withAccessKeySecretAndCachePath(
"YOUR_ACCESS_KEY_ID", "YOUR_ACCESS_KEY_SECRET", "");
SDKNativeEngine sdkNativeEngine;
try {
sdkNativeEngine = SDKNativeEngine(sdkOptions);
SDKNativeEngine.sharedInstance = sdkNativeEngine;
} on InstantiationException {
// Handle exception.
}
runApp(MyApp());
}
I'm writing a widget test in my Flutter app. I'able to find the button using key or text or widget type but when I tap it, it gives Bad State No element error. Below is my test source code. I can also see the element in tester object while debugging under allWidgets item.
class MockSpeechRecognizer extends Mock implements SpeechRecognizer {}
void main() {
final TestWidgetsFlutterBinding binding = TestWidgetsFlutterBinding.ensureInitialized();
setUpAll(() {
const MethodChannel('plugins.flutter.io/shared_preferences')
.setMockMethodCallHandler((MethodCall methodCall) async {
if (methodCall.method == 'getAll') {
return <String, dynamic>{}; // set initial values here if desired
}
return null;
});
setupLocator();
});
group('DashboardView Test | ', () {
testWidgets('Build Dashboard view and change keyword', (WidgetTester tester) async {
final Preferences preferences=Preferences();
preferences.keyword='hello';
final MockSpeechRecognizer speechService = MockSpeechRecognizer();
when(speechService.isServiceRunning).thenReturn(true);
locator.unregister<SpeechRecognizer>();
locator.registerLazySingleton<SpeechRecognizer>(() => speechService);
locator<LocalStorageService>().setUserPreferences(preferences);
// Build our app and trigger a frame.
binding.window.physicalSizeTestValue = Size(600, 300);
await tester.pumpWidget(MaterialApp(home:Dashboard()));
await tester.pumpAndSettle();
expect(find.byType(Dashboard),findsOneWidget);
await tester.tap(find.byKey(const Key('ChangeKeyword')));
});
});
}
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following StateError was thrown running a test:
Bad state: No element
When the exception was thrown, this was the stack:
#0 Iterable.single (dart:core/iterable.dart:554:25)
#1 WidgetController._getElementPoint (package:flutter_test/src/controller.dart:646:47)
#2 WidgetController.getCenter (package:flutter_test/src/controller.dart:618:12)
#3 WidgetController.tap (package:flutter_test/src/controller.dart:256:18)
#4 main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_test.dart:52:20)
<asynchronous suspension>
#5 main.<anonymous closure>.<anonymous closure> (file:///E:/Siak/Meow/meow-phone-finder/test/Widgets/dashboardView_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
Where do you define the Button, have you set the Key parameter?
await tester.pumpWidget(MaterialApp(home:
Container(child:
Button(
key: Key("ChangeKeyword"),
onTap: () => {},
child: Text("Press me"),
),
),
));
I have created a route to the home screen which should be displayed after login is successful. However, my circular bar just keeps moving (indicating isLoading stage) and the home screen does not show up in the simulator.
I am aware that the login is successful since my response variable does print the information in the console that it accesses after login.
On pressing the login the button 2 main issues are displayed:
1) Exception thrown while handling a gesture
2) Unhandled Exception: Failed assertion: boolean expression must not be null
I am unable to solve this these 2 issues. Any help would be great.
Thanks in advance!
There is no compilation error. The following are the main issues shown after pressing the login button (complete stack tree and message posted later in the question):
flutter: The following ArgumentError was thrown while handling a gesture:
flutter: Invalid argument (onError): Error handler must accept one Object or one Object and a StackTrace as
flutter: arguments, and return a a valid result: Closure: (Exception) => void
Unhandled Exception: Failed assertion: boolean expression must not be null
The console message posted later refers to 3 files. I have posted important code of the files below.
File: login_screen.dart
import 'dart:ui';
import 'package:flutter/material.dart';
class LoginScreen extends StatefulWidget {
#override
State<StatefulWidget> createState() {
return new LoginScreenState();
}
}
class LoginScreenState extends State<LoginScreen>
implements LoginScreenContract, AuthStateListener {
BuildContext _ctx;
bool _isLoading = false;
final formKey = new GlobalKey<FormState>();
final scaffoldKey = new GlobalKey<ScaffoldState>();
String _password, _username;
LoginScreenPresenter _presenter;
LoginScreenState() {
_presenter = new LoginScreenPresenter(this);
var authStateProvider = new AuthStateProvider();
authStateProvider.subscribe(this);
}
void _submit() {
final form = formKey.currentState;
if (form.validate()) {
setState(() => _isLoading = true);
form.save();
_presenter.doLogin(_username, _password);
}
}
void _showSnackBar(String text) {
scaffoldKey.currentState
.showSnackBar(new SnackBar(content: new Text(text)));
}
#override
onAuthStateChanged(AuthState state) {
if(state == AuthState.LOGGED_IN)
Navigator.of(_ctx).pushReplacementNamed("/home");
}
#override
Widget build(BuildContext context) {
_ctx = context;
....(UI for login screen)
#override
void onLoginError(String errorTxt) {
_showSnackBar(errorTxt);
setState(() => _isLoading = false);
}
#override
void onLoginSuccess(User user) async {
HomeScreen()));
_showSnackBar(user.toString());
setState(() => _isLoading = false);
var db = new DatabaseHelper();
await db.saveUser(user);
var authStateProvider = new AuthStateProvider();
HomeScreen()));
authStateProvider.notify(AuthState.LOGGED_IN);
onAuthStateChanged(AuthState.LOGGED_IN);
}
}
File: login_screen_presenter.dart
import 'package:better_login/rest_ds.dart';
import 'package:better_login/user.dart';
abstract class LoginScreenContract {
void onLoginSuccess(User user);
void onLoginError(String errorTxt);
}
class LoginScreenPresenter {
LoginScreenContract _view;
RestDatasource api = new RestDatasource();
LoginScreenPresenter(this._view);
doLogin(String username, String password) {
api.login(username, password).then((User user) {
_view.onLoginSuccess(user);
}).catchError((Exception error) =>
_view.onLoginError(error.toString()));
}
}
File: rest_ds.dart
static final LOGIN_URL = "https://legacy- api.example.com/v1/auth/login";
Future<User> login(String username, String password) {
return _netUtil.post(LOGIN_URL, body: {
"username": username,
"password": password
}).then((dynamic res) {
print(res.toString());
if(res["error"]){ throw new Exception(res["error_msg"]);}
return new User.map(res["user"]);
});
}
}
This is the complete info displayed in the console:
flutter: The following ArgumentError was thrown while handling a gesture:
flutter: Invalid argument (onError): Error handler must accept one Object or one Object and a StackTrace as
flutter: arguments, and return a a valid result: Closure: (Exception) => void
flutter:
flutter: When the exception was thrown, this was the stack:
flutter: #2 LoginScreenPresenter.doLogin (package:better_login/login_screen_presenter.dart:17:8)
flutter: #3 LoginScreenState._submit (package:better_login/login_screen.dart:41:18)
flutter: #4 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:511:14)
flutter: #5 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:566:30)
flutter: #6 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:166:24)
flutter: #7 TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:240:9)
flutter: #8 TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:177:9)
flutter: #9 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:436:9)
flutter: #10 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
flutter: #11 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
flutter: #12 _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:221:19)
flutter: #13 _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:199:22)
flutter: #14 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
flutter: #15 _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
flutter: #16 _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
flutter: #20 _invoke1 (dart:ui/hooks.dart:233:10)
flutter: #21 _dispatchPointerDataPacket (dart:ui/hooks.dart:154:5)
flutter: (elided 5 frames from package dart:async)
flutter:
flutter: Handler: onTap
flutter: Recognizer:
flutter: TapGestureRecognizer#398b8(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
flutter: Offset(194.0, 504.0), sent tap down)
flutter: ════════════════════════════════════════════════════════════════════════════════════════════════════
flutter: {status: success, message: Authentication Success, executionTime: 0.052, data: {token: U2FsdGVkX19ZQS5wQXRYWTkh2o4PyrtmhS4kELJO0WsEBDbn30G9Oig/13fzHzqZ, custKey: anb2mNXFERnJ4IQW....(rest is info got on login)
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: Failed assertion: boolean expression must not be null
#0 RestDatasource.login.<anonymous closure> (package:better_login/rest_ds.dart:21:13)
#1 _rootRunUnary (dart:async/zone.dart:1132:38)
#2 _CustomZone.runUnary (dart:async/zone.dart:1029:19)
#3 _FutureListener.handleValue (dart:async/future_impl.dart:126:18)
#4 Future._propagateToListeners.handleValueCallback (dart:async/future_impl.dart:639:45)
#5 Future._propagateToListeners (dart:async/future_impl.dart:668:32)
#6 Future._complete (dart:async/future_impl.dart:473:7)
#7 _SyncCompleter.complete (dart:async/future_impl.dart:51:12)
#8 _AsyncAwaitCompleter.complete (dart:async-patch/async_patch.dart:28:18)
#9 _completeOnAsyncReturn (dart:async-patch/async_patch.dart:294:13)
#10 _withClient (package:http/http.dart)
<asynchronous suspension>
#11 post (package:http/http.dart:69:5)
#12 NetworkUtil.post (package:better_login/network_util.dart<…>
There are several issues in your code:
catchError param is not of type Exception is of type Object. You can use the second param of catchError, test to filter errors received. This is the cause of the crash report trace The following ArgumentError was thrown while handling a gestur.
the main cause of the crash is here if(res["error"]){ throw new Exception(res["error_msg"]);}, because the res["error"] is probably null. To fix it change it to if(res["error"] != null) .....
Refactoring points:
you don't need to save the build context in a _ctx variable, any subclass of State has access to it's main context via context property.