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());
}
Related
Here is the main() function. Here is the initializisation of the "flutter_isolate" library
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(const MyApp());
}
...
class BTConnection {
BluetoothConnection? c;
Future<void> connect(address) async {
print('Connecting to the device ...');
BluetoothConnection connection =
await BluetoothConnection.toAddress(address);
c = connection;
print('Connected to the device');
FlutterIsolate.spawn(listenToData, connection);
}
Future<void> disconnect() async {
if (c != null) {
await c?.finish();
print("disconnected from device");
} else {
print("There is no bluetooth connection to disconnect");
}
}
#pragma('vm:entry-point')
Future<void> listenToData(connection) async {
print("listening ...");
await connection.input?.listen((Uint8List data) {
print('Data incoming: ${ascii.decode(data)}');
connection.output.add(data); // Sending data
}).onDone(() {
print('Disconnected by remote request');
});
}
}
Whenever I run the code and enter the correct MAC address in the text field, the function connect() is called and after a few seconds the message "Connected to the device" is printed. The following error message is then output:
E/flutter (26066): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Null check operator used on a null value
E/flutter (26066): #0 FlutterIsolate.spawn
flutter_isolate.dart:28
E/flutter (26066): #1 BTConnection.connect
main.dart:110
E/flutter (26066): <asynchronous suspension>
E/flutter (26066): #2 _HomePageState.build.<anonymous closure>
main.dart:70
E/flutter (26066): <asynchronous suspension>
E/flutter (26066):
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'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
I am trying to add native ads using the plugin flutter_native_admob but I always get this error:
E/flutter ( 6504): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel flutter_native_admob)
E/flutter ( 6504): #0 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:319:7)
E/flutter ( 6504): <asynchronous suspension>
E/flutter ( 6504): #1 NativeAdmob.initialize (package:flutter_native_admob/flutter_native_admob.dart:105:20)
E/flutter ( 6504): #2 HomePageState.initState (package:spanglishcards/view/card/HomePage.dart:67:19)
E/flutter ( 6504): #3 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4355:58)
I tried to add it in my Home page:
class HomePage extends StatefulWidget {
HomePage({
this.user,
});
final User user;
#override
State<StatefulWidget> createState() => HomePageState();
}
class HomePageState extends State<HomePage> {
final _nativeAdmobs = NativeAdmob();
Future initState() {
super.initState();
_nativeAdmobs.initialize(appID:"ca-app-pub-XXX~XXX" );
}
}
And also in the main.dart:
final _nativeAdmobs = NativeAdmob();
void main(){
WidgetsFlutterBinding.ensureInitialized();
_nativeAdmobs.initialize(appID:"ca-app-pub-XXX~XXX" );
runApp(MyApp());
}
I also tried to run flutter clean / flutter run before just in case, but it doesn't work either. Any solution?
To discard issues with my appID, the plugin firebase_admob (doesn't support native ads) works.
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.