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):
Related
I am trying to implement notifications on flutter but I am getting a weird error:
I am calling the following function:
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
I am getting the following error:
Instance member 'initialize' can't be accessed using static access.
here is the error log:
: Error: Member not found: 'FlutterLocalNotificationsPlugin.initialize'.
lib/navigator_view.dart:81
FlutterLocalNotificationsPlugin.initialize(initializationsSettings,
^^^^^^^^^^
Restarted application in 271ms.
I am trying to follow this video: https://youtu.be/AUU6gbDni4Q?t=845
I was able to get pass the initial error by doing this::
initInfo() {
var androidInitialize =
const AndroidInitializationSettings("#mipmap/ic_launcher");
var iOSInitialize = const IOSInitializationSettings();
var initializationsSettings =
InitializationSettings(android: androidInitialize, iOS: iOSInitialize);
var fln = FlutterLocalNotificationsPlugin(); // new code
fln.initialize(initializationsSettings,
onSelectNotification: (String? payload) async {
try {
if (payload != null && payload.isNotEmpty) ;
} catch (e) {
print(e);
}
return;
});
}
but now I am getting the following error:
/flutter (23250): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel dexterous.com/flutter/local_notifications)
E/flutter (23250): #0 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:294
E/flutter (23250): <asynchronous suspension>
E/flutter (23250): #1 AndroidFlutterLocalNotificationsPlugin.initialize
package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:85
E/flutter (23250): <asynchronous suspension>
E/flutter (23250):
should I not be doing this change?
im new in flutter and i want to consume my Api to display data in my app ,
i made this in service class :
class Service {
final String apiUrl = "http://localhost:3000/Todo";
Future<List<Todo>> getCases() async {
Response res = await get(Uri.parse(apiUrl));
if (res.statusCode == 200) {
List<dynamic> body = jsonDecode(res.body);
List<Todo> todo = body.map((dynamic item) => Todo.fromJson(item)).toList();
return todo;
} else {
throw "Failed to load cases list";
}
}
the Terminal shows me that there is an error in Response res = await get(Uri.parse(apiUrl));
The Error
[ERROR:flutter/shell/common/shell.cc(93)] Dart Unhandled Exception: Connection failed, stack trace: #0 IOClient.send (package:http/src/io_client.dart:88:7)
<asynchronous suspension>
#1 BaseClient._sendUnstreamed (package:http/src/base_client.dart:93:32)
<asynchronous suspension>
#2 _withClient (package:http/http.dart:164:12)
<asynchronous suspension>
#3 Service.getCases (package:restnv/Service/service.dart:11:20)
<asynchronous suspension>
#4 _FutureBuilderState._subscribe.<anonymous closure> (package:flutter/src/widgets/async.dart:627:33)
NB
i get my Api from Npm json-server
how can i fix it
This problem might be because of your local host
//final String ApiUrl = "http://localhost:3000/Todo"
This will not work in physical devices, so you should try local host to
10.0.2.2:3000
This will work in emulator.
Getting a weird error while using signInWithCredential(), but I am able to sign in by signInAnonymously()
Have tried searching and remaking app in facebookDeveloper account.
My Function:
Future<UserCredential> _signInWithFacebook() async {
final loginResult = await FacebookAuth.instance.login(permissions: [
'email',
'public_profile',
]);
if (loginResult.status == LoginStatus.success) {
final accessToken = loginResult.accessToken!.token;
final OAuthCredential credential =
FacebookAuthProvider.credential(accessToken);
return await FirebaseAuth.instance
.signInWithCredential(credential)
.then((value) {
Navigator.pushReplacementNamed(context, '/home');
return value;
});
} else {
return FirebaseAuth.instance.signInAnonymously();
}
}
Error:
FLTFirebaseAuth: An error occurred while calling method Auth#signInWithCredential, errorOrNil => (null)
[VERBOSE-2:ui_dart_state.cc(198)] Unhandled Exception: [firebase_auth/unknown] An unknown error has occurred.
#0 StandardMethodCodec.decodeEnvelope
package:flutter/…/services/message_codecs.dart:607
#1 MethodChannel._invokeMethod
package:flutter/…/services/platform_channel.dart:167
<asynchronous suspension>
#2 MethodChannel.invokeMapMethod
package:flutter/…/services/platform_channel.dart:367
<asynchronous suspension>
#3 MethodChannelFirebaseAuth.signInWithCredential
package:firebase_auth_platform_interface/…/method_channel/method_channel_firebase_auth.dart:433
<asynchronous suspension>
#4 FirebaseAuth.signInWithCredential
package:firebase_auth/src/firebase_auth.dart:497
<asynchronous suspension>
The following steps can be helpful if you haven't tried it yet -
Check if the firebase app is instantiated at the beginning -> .initializeApp()
Firebase Auth doesn't work without initialization
If the above two doesn't work, replace google-services.json with a new one. Do a clean build
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 tried to use ovprogresshud (https://pub.dev/packages/ovprogresshud) to show download progress. I used flutter_downloader (https://pub.dev/packages/flutter_downloader) for download.
I try to update progress via an Isolate, but receive errors.
(If I call Progresshud.showWithStatusdirectly in my code, say before download, it works)
My code:
ReceivePort _port = ReceivePort();
...
IsolateNameServer.registerPortWithName(
_port.sendPort, 'downloader_send_port');
_port.listen(
(dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
if (status == DownloadTaskStatus.complete) {
} else if (status == DownloadTaskStatus.running) {
Progresshud.showWithStatus("%$progress Downloaded");
}
},
onDone: () {
checkIfDictionaryUnzipped(DBFilePath);
},
onError: (error) {},
);
The error I receive:
Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'android.view.ViewParent android.view.ViewGroup.getParent()' on a null object reference, null)
E/flutter (29114): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (29114): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:321:33)
E/flutter (29114): <asynchronous suspension>
E/flutter (29114): #2 Progresshud.showWithStatus (package:ovprogresshud/progresshud.dart:18:27)
E/flutter (29114): <asynchronous suspension>
....
check important note here
Important note: your UI is rendered in the main isolate, while download events come from a background isolate (in other words, codes in callback are run in the background isolate), so you have to handle the communication between two isolates.
Check Example,
ReceivePort _port = ReceivePort();
#override
void initState() {
super.initState();
IsolateNameServer.registerPortWithName(_port.sendPort, 'downloader_send_port');
_port.listen((dynamic data) {
String id = data[0];
DownloadTaskStatus status = data[1];
int progress = data[2];
setState((){ });
});
FlutterDownloader.registerCallback(downloadCallback);
}
#override
void dispose() {
IsolateNameServer.removePortNameMapping('downloader_send_port');
super.dispose();
}
static void downloadCallback(String id, DownloadTaskStatus status, int progress) {
final SendPort send = IsolateNameServer.lookupPortByName('downloader_send_port');
send.send([id, status, progress]);
}