How to use dart:ffi in Flutter? - flutter

I'm stuck on how I would implement dart::ffi in Flutter, specifically the hello_world example.
Starting with the basic flutter create project (and an already compiled hello_world.dll) just trying:
void main() {
final dylib = ffi.DynamicLibrary.open('hello_world.dll');
final HelloWorld hello = dylib
.lookup<ffi.NativeFunction<hello_world_func>>('hello_world')
.asFunction();
hello();
runApp(MyApp());
}
leads to:
Launching lib\main.dart on sdk gphone x86 arm in debug mode...
package:testing_flutter/main.dart:1
√ Built build\app\outputs\flutter-apk\app-debug.apk.
Connecting to VM Service at ws://127.0.0.1:61913/wRTGFN76kik=/ws
E/flutter (11980): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: Invalid argument(s): Failed to load dynamic library (dlopen failed: library "hello_world.dll" not found)
E/flutter (11980): #0 _open (dart:ffi-patch/ffi_dynamic_library_patch.dart:11:55)
E/flutter (11980): #1 new DynamicLibrary.open (dart:ffi-patch/ffi_dynamic_library_patch.dart:20:12)
E/flutter (11980): #2 main
package:testing_flutter/main.dart:8
E/flutter (11980): #3 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:140:25)
E/flutter (11980): #4 _rootRun (dart:async/zone.dart:1354:13)
E/flutter (11980): #5 _CustomZone.run (dart:async/zone.dart:1258:19)
E/flutter (11980): #6 _runZoned (dart:async/zone.dart:1788:10)
E/flutter (11980): #7 runZonedGuarded (dart:async/zone.dart:1776:12)
E/flutter (11980): #8 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:133:5)
E/flutter (11980): #9 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (11980): #10 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (11980):
Would I also need a .dylib version, something like what's in the example?
var libraryPath =
path.join(Directory.current.path, 'hello_library', 'libhello.so');
if (Platform.isMacOS)
libraryPath =
path.join(Directory.current.path, 'hello_library', 'libhello.dylib');
if (Platform.isWindows)
libraryPath = path.join(
Directory.current.path, 'hello_library', 'Debug', 'hello.dll');

Related

how to use rootBundle to load config in flutter

I am using rootBundle to load config in flutter(2.5.x), this is my code:
Future<void> main() async {
final jsonStr = await rootBundle.loadString("assets/static/emoji-flags.json", cache: false);
}
and I already config the path in pubspec.yaml like this:
flutter:
uses-material-design: true
assets:
- assets/translations/
- assets/static/
but this code running error like this:
E/flutter (14207): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Null check operator used on a null value
E/flutter (14207): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:222:39)
E/flutter (14207): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:68:33)
E/flutter (14207): #2 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:166:18)
E/flutter (14207): #3 main (package:flutter_learn/main.dart:10:36)
E/flutter (14207): #4 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
E/flutter (14207): #5 _rootRun (dart:async/zone.dart:1428:13)
E/flutter (14207): #6 _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (14207): #7 _runZoned (dart:async/zone.dart:1863:10)
E/flutter (14207): #8 runZonedGuarded (dart:async/zone.dart:1851:12)
E/flutter (14207): #9 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:141:5)
E/flutter (14207): #10 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:283:19)
E/flutter (14207): #11 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:184:12)
E/flutter (14207):
what should I do to load this config success? Am I missing something?
This is my environment reader, I map my json file to the data model.
import 'package:flutter/services.dart';
static Future<void> initializeApp(String? env) async {
env = env ?? "development";
final configString = await rootBundle.loadString('assets/config/env.json');
final jsonMap = json.decode(configString);
_config = ConfigModel.fromMap(jsonMap[env]);
}

How to save values from query in shared_preferences with conditional statement flutter

I have a query function for data from the database that comes with the id number from the database, then the id is saved in shared_preferences in case the new id that comes from the database is larger than the old id that was in the shared_preferences previously.But after running the code, the following problem comes:
E/flutter (30884): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: NoSuchMethodError: Class 'String' has no instance method '<'.
E/flutter (30884): Receiver: ""
E/flutter (30884): Tried calling: <(7)
E/flutter (30884): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:51:5)
E/flutter (30884): #1 AddCommentsState.getLogin.<anonymous closure> (package:flutter_apptestqeuriy/AddComment.dart:84:46)
E/flutter (30884): #2 State.setState (package:flutter/src/widgets/framework.dart:1240:30)
E/flutter (30884): #3 AddCommentsState.getLogin (package:flutter_apptestqeuriy/AddComment.dart:78:5)
E/flutter (30884): <asynchronous suspension>
E/flutter (30884): #4 AddCommentsState.initState.<anonymous closure> (package:flutter_apptestqeuriy/AddComment.dart:57:9)
E/flutter (30884): #5 interval.function (package:flutter_apptestqeuriy/AddComment.dart:21:9)
E/flutter (30884): #6 _rootRun (dart:async/zone.dart:1182:47)
E/flutter (30884): #7 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (30884): #8 _CustomZone.runGuarded (dart:async/zone.dart:997:7)
E/flutter (30884): #9 _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1037:23)
E/flutter (30884): #10 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (30884): #11 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (30884): #12 _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1021:23)
E/flutter (30884): #13 Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (30884): #14 _Timer._runTimers (dart:isolate-patch/timer_impl.dart:397:19)
E/flutter (30884): #15 _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:428:5)
E/flutter (30884): #16 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (30884):
This is the code used to query from the database:
var user_id;
var my_pre_id;
Future<String> getLogin() async {
var response = await http.get(Uri.encodeFull("http://xxxxxxxxxxx/Application.php"),);
setState(() {
var convertDataToJson = json.decode(response.body);
data = convertDataToJson['result'];
if (data != null) {
user_id = int.parse(data[0]['id']);
my_pre_id = _myPreferences.id;
if (my_pre_id == null || my_pre_id < user_id ){
_myPreferences.id = user_id;
_myPreferences.commit();
// print("tappeeeeedddd $my_pre_id");
}
}
});
}
Does anyone know the cause of the problem?
I think the issue comes from my_pre_id < user_id where my_pre_id is actually a String. You might want to do an int.parse() on it as well or change its type in the class.

Unhandled Exception: MissingPluginException(No implementation found for method log on channel testfairy)

I'm trying to build an Android app, but receive an error MissingPluginException(No implementation found for method log on channel testfairy):
E/flutter ( 8121): [ERROR:flutter/lib/ui/ui_dart_state.cc(177)] Unhandled Exception: MissingPluginException(No implementation found for method initialize on channel dexterous.com/flutter/local_notifications)
E/flutter ( 8121): #0 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:157:7)
E/flutter ( 8121): <asynchronous suspension>
E/flutter ( 8121): #1 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:332:12)
E/flutter ( 8121): #2 AndroidFlutterLocalNotificationsPlugin.initialize (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:67:27)
E/flutter ( 8121): #3 FlutterLocalNotificationsPlugin.initialize (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:97:13)
E/flutter ( 8121): #4 NotificationHelper.initNotifications (package:boxview_mobile_flutter/services/notification_helper.dart:23:37)
E/flutter ( 8121): #5 new Routes (package:boxview_mobile_flutter/routes.dart:49:26)
E/flutter ( 8121): #6 main (package:boxview_mobile_flutter/main.dart:4:7)
E/flutter ( 8121): #7 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:231:25)
E/flutter ( 8121): #8 _rootRun (dart:async/zone.dart:1190:13)
E/flutter ( 8121): #9 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter ( 8121): #10 _runZoned (dart:async/zone.dart:1630:10)
E/flutter ( 8121): #11 runZonedGuarded (dart:async/zone.dart:1618:12)
E/flutter ( 8121): #12 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:223:5)
E/flutter ( 8121): #13 _startIsolate.<anonymous closure> (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter ( 8121): #14 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
Current version of TestFairy plugin: testfairy: ^2.0.1
Flutter (Channel stable, 1.22.2)
Dart version 2.10.2.
Also, I've added analysis_options.yaml:
analyzer:
enable-experiment:
- non-nullable
I run the app with the command flutter run --enable-experiment=non-nullable --no-sound-null-safety.
How to resolve this error?
#Akif has pointed in the right direction of a reason for the problem. In fact, this was due to the local_notifications plugin. I managed to solve this problem by switching the flutter to the beta channel (Flutter 1.23.0-18.1.pre • channel beta).

Flutter local notifications throwing an error

While trying to show the notifications from flutter_local_notification it throws the following error:
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): Failed to handle method call
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): java.lang.NullPointerException: Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.setSmallIcon(FlutterLocalNotificationsPlugin.java:188)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.createNotification(FlutterLocalNotificationsPlugin.java:146)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.showNotification(FlutterLocalNotificationsPlugin.java:688)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.show(FlutterLocalNotificationsPlugin.java:827)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin.onMethodCall(FlutterLocalNotificationsPlugin.java:750)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.plugin.common.MethodChannel$IncomingMethodCallHandler.onMessage(MethodChannel.java:226)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.embedding.engine.dart.DartMessenger.handleMessageFromDart(DartMessenger.java:85)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at io.flutter.embedding.engine.FlutterJNI.handlePlatformMessage(FlutterJNI.java:631)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.MessageQueue.nativePollOnce(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.MessageQueue.next(MessageQueue.java:325)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.os.Looper.loop(Looper.java:142)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at android.app.ActivityThread.main(ActivityThread.java:6494)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at java.lang.reflect.Method.invoke(Native Method)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
E/MethodChannel#dexterous.com/flutter/local_notifications(10962): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)
E/flutter (10962): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: PlatformException(error, Attempt to invoke virtual method 'int java.lang.Integer.intValue()' on a null object reference, null)
E/flutter (10962): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:569:7)
E/flutter (10962): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:156:18)
E/flutter (10962): <asynchronous suspension>
E/flutter (10962): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:329:12)
E/flutter (10962): #3 AndroidFlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/platform_flutter_local_notifications.dart:137:21)
E/flutter (10962): #4 FlutterLocalNotificationsPlugin.show (package:flutter_local_notifications/src/flutter_local_notifications_plugin.dart:136:13)
E/flutter (10962): #5 NotificationPlugin.showNotification (package:pig_salang/models/notification_plugin.dart:94:43)
E/flutter (10962): #6 WelcomeScreen.build.<anonymous closure> (package:pig_salang/screens/welcome_screen.dart:42:36)
E/flutter (10962): #7 WelcomeScreen.build.<anonymous closure> (package:pig_salang/screens/welcome_screen.dart:41:26)
E/flutter (10962): #8 _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:779:19)
E/flutter (10962): #9 _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:862:36)
E/flutter (10962): #10 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:182:24)
E/flutter (10962): #11 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:504:11)
E/flutter (10962): #12 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:282:5)
E/flutter (10962): #13 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:217:7)
E/flutter (10962): #14 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:475:9)
E/flutter (10962): #15 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:76:12)
E/flutter (10962): #16 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_router.dart:122:9)
E/flutter (10962): #17 _LinkedHashMapMixin.forEach (dart:collection-patch/compact_hash.dart:379:8)
E/flutter (10962): #18 PointerRouter._dispatchEventToRoutes (package:flutter/src/gestures/pointer_router.dart:120:18)
E/flutter (10962): #19 PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:106:7)
E/flutter (10962): #20 GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:218:19)
E/flutter (10962): #21 GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:198:22)
E/flutter (10962): #22 GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:156:7)
E/flutter (10962): #23 GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:102:7)
E/flutter (10962): #24 GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:86:7)
E/flutter (10962): #25 _rootRunUnary (dart:async/zone.dart:1196:13)
E/flutter (10962): #26 _CustomZone.runUnary (dart:async/zone.dart:1085:19)
E/flutter (10962): #27 _CustomZone.runUnaryGuarded (dart:async/zone.dart:987:7)
E/flutter (10962): #28 _invoke1 (dart:ui/hooks.dart:275:10)
E/flutter (10962): #29 _dispatchPointerDataPacket (dart:ui/hooks.dart:184:5)
E/flutter (10962):
As far as I have researched, the similar errors were shown because of the icon. I have added used every possible way to add icons, but it is not throwing the error constantly. Obviously, I rerun the app after each changes, to make sure I don't get the error.
My code looks like:
initializePlatformSpecifics() {
var initializeAndroidSettings = AndroidInitializationSettings('app_icon'); <--- Here
var initializeIOSSettings = IOSInitializationSettings(
requestAlertPermission: false,
requestBadgePermission: true,
requestSoundPermission: true,
onDidReceiveLocalNotification: (id, title, body, payload) async {
ReceivedNotification receivedNotification = ReceivedNotification(
id: id, title: title, body: body, payload: payload);
didReceivedLocalNotificationSubject.add(receivedNotification);
},
);
initializeSettings = InitializationSettings(
initializeAndroidSettings, initializeIOSSettings);
}
I followed the tutorial. The thing is when I try to show the notification, it shows the above traceback.
I made notification icons in Android Studio -> app -> main -> res -> Image Asssets -> Notifications icon, then I made icon with name app_icon which I used to intialize the notification.
As it was not working, I also tried :
var initializeAndroidSettings = AndroidInitializationSettings('#mipmap/ic_launcher');
It also did not work. Any help would be appreciated!!!
'app_icon' was given for reference and it actually depends on where you image file is located, if you are using the default icon in mipmap folder named as ic_launcher for now then try the below code. Do let me know if it helps.
var initializeAndroidSettings
=AndroidInitializationSettings('mipmap/ic_launcher');

Unhandled Exception: WebSocketException: Connection to 'http://10.5.11.88:7777/socketcluster/#' was not upgraded to websocket

Here is my Client code and server is in c++. But when i am trying to connect this client to server it is throwing an error that websocket is not upgrading. The server is running i have checked with js client.
Code for client
import 'package:socketcluster_client/socketcluster_client.dart';
import 'dart:async';
class MyListener extends BasicListener {
#override
void onAuthentication(Socket socket, bool status) {
print('onAuthentication: socket $socket status $status');
}
#override
void onConnectError(Socket socket, e) {
print('onConnectError: socket $socket e $e');
}
#override
void onConnected(Socket socket) {
print('onConnected: socket $socket');
new Timer.periodic(const Duration(seconds: 2), (_) {
print('Attempting to send');
socket.emit('sampleClientEvent',
{'message': 'This is an object with a message property'});
});
}
#override
void onDisconnected(Socket socket) {
print('onDisconnected: socket $socket');
}
#override
void onSetAuthToken(String token, Socket socket) {
print('onSetAuthToken: socket $socket token $token');
socket.authToken = token;
}
}
main() async {
var socket = await Socket.connect('ws://10.5.11.88:7777/socketcluster/',
listener: new MyListener());
socket.on('rand', (name, data, ack) {
print('got message $data from event $name');
ack(name, 'No error', 'Hi there buddy');
});
}
I have tried https://github.com/flutter/flutter/issues/11444 but it is not working.
Error Log
Launching lib\main.dart on AOSP on IA Emulator in debug mode...
Running Gradle task 'assembleDebug'...
√ Built build\app\outputs\apk\debug\app-debug.apk.
Installing build\app\outputs\apk\app.apk...
Syncing files to device AOSP on IA Emulator...
E/flutter ( 5399): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled
Exception: WebSocketException: Connection to
'http://10.5.11.88:7777/socketcluster/#' was not upgraded to websocket
E/flutter ( 5399): #0 _WebSocketImpl.connect.<anonymous closure>.error
(dart:_http/websocket_impl.dart:1054:9)
E/flutter ( 5399): #1 _WebSocketImpl.connect.<anonymous closure>
(dart:_http/websocket_impl.dart:1063:14)
E/flutter ( 5399): #2 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 5399): #3 _CustomZone.runUnary
(dart:async/zone.dart:1031:19)
E/flutter ( 5399): #4 _FutureListener.handleValue
(dart:async/future_impl.dart:139:18)
E/flutter ( 5399): #5 Future._propagateToListeners.handleValueCallback
(dart:async/future_impl.dart:680:45)
E/flutter ( 5399): #6 Future._propagateToListeners
(dart:async/future_impl.dart:709:32)
E/flutter ( 5399): #7 Future._completeWithValue
(dart:async/future_impl.dart:524:5)
E/flutter ( 5399): #8 Future.wait.<anonymous closure>
(dart:async/future.dart:400:22)
E/flutter ( 5399): #9 _rootRunUnary (dart:async/zone.dart:1134:38)
E/flutter ( 5399): #10 _CustomZone.runUnary
(dart:async/zone.dart:1031:19)
E/flutter ( 5399): #11 _FutureListener.handleValue
(dart:async/future_impl.dart:139:18)
E/flutter ( 5399): #12 Future._propagateToListeners.handleValueCallback
(dart:async/future_impl.dart:680:45)
E/flutter ( 5399): #13 Future._propagateToListeners
(dart:async/future_impl.dart:709:32)
E/flutter ( 5399): #14 Future._completeWithValue
(dart:async/future_impl.dart:524:5)
E/flutter ( 5399): #15 Future._asyncComplete.<anonymous closure>
(dart:async/future_impl.dart:554:7)
E/flutter ( 5399): #16 _rootRun (dart:async/zone.dart:1126:13)
E/flutter ( 5399): #17 _CustomZone.run (dart:async/zone.dart:1023:19)
E/flutter ( 5399): #18 _CustomZone.runGuarded
(dart:async/zone.dart:925:7)
E/flutter ( 5399): #19 _CustomZone.bindCallbackGuarded.<anonymous
closure> (dart:async/zone.dart:965:23)
E/flutter ( 5399): #20 _microtaskLoop
(dart:async/schedule_microtask.dart:43:21)
E/flutter ( 5399): #21 _startMicrotaskLoop
(dart:async/schedule_microtask.dart:52:5)
E/flutter ( 5399):
Actually strict application load balancer policy was applied on AWS/server
Relaxing it solved the issue