I have a simple dart class as follows:
import 'package:flutter/material.dart';
class UiUtils {
// TEMPORARY FOR UNIT TEST PURPOSES ONLY
int addition(int x, int y) {
return x + y;
}
}
(Note: The above is a sample, the actual class does have more than that temp function.)
My pubspec.yml file contains the following:
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: ^0.17.0
# The following adds the Cupertino Icons font to your application.
# Use with the CupertinoIcons class for iOS style icons.
cupertino_icons: ^1.0.2
get_it: ^7.1.3
provider: ^6.0.1
mockito: ^5.0.16
I have a dependency locator file as such:
import 'package:get_it/get_it.dart';
import 'package:quiz_test/utils/UiUtils.dart';
GetIt dependencyLocator = GetIt.instance;
void setupDependencyLocator() {
//dependencyLocator.registerSingleton(() => UiUtils());
dependencyLocator.registerFactory(() => UiUtils());
}
Finally, in main.dart I have the following:
void main() {
setupDependencyLocator();
runApp(MyApp());
}
(There is of course more code than this).
As it is displayed, the code works fine, however if I change the dependancy_locator file from the current factory method to the singleton instead (i.e. comment out one to enable the other) I get the following error:
[VERBOSE-2:ui_dart_state.cc(209)] Unhandled Exception: type '_ServiceFactory<() => UiUtils, void, void>' is not a subtype of type '_ServiceFactory<Object, dynamic, dynamic>' of 'value'
#0 _LinkedHashMapMixin.[]= (dart:collection-patch/compact_hash.dart)
#1 _GetItImplementation._register (package:get_it/get_it_impl.dart:844:35)
#2 _GetItImplementation.registerSingleton (package:get_it/get_it_impl.dart:587:5)
#3 setupDependencyLocator (package:quiz_test/utils/dependency_locator.dart:7:21)
#4 main (package:quiz_test/main.dart:13:3)
#5 _runMainZoned.<anonymous closure>.<anonymous closure> (dart:ui/hooks.dart:145:25)
#6 _rootRun (dart:async/zone.dart:1428:13)
#7 _CustomZone.run (dart:async/zone.dart:1328:19)
#8 _runZoned (dart:async/zone.dart:1863:10)
#9 runZonedGuarded (dart:async/zone.dart:1851:12)
#10 _runMainZoned.<anonymous closure> (dart:ui/hooks.dart:141:5)
#11 _delayEntrypointInvocation.<anonymous closure> (dart:isolate-patch/isolate_patch.<…>
Can anyone please help me to understand why I cannot use the singleton call rather than the factory one? My thought process is that I do not need a unique instance of this class, which is what I believe factory will give me, I just need a single instance of it for any classes that require it.
Any help is greatly appreciated.
I was able to resolve this by doing the following:
dependencyLocator.registerSingleton<UiUtils>(UiUtils());
So, my dependencyLocator class now looks like this:
import 'package:get_it/get_it.dart';
import 'package:quiz_test/utils/UiUtils.dart';
GetIt dependencyLocator = GetIt.instance;
void setupDependencyLocator() {
dependencyLocator.registerSingleton<UiUtils>(UiUtils());
}
I hope this helps someone else from getting stuck!
Related
For the sake of the argument let's say I have an implementation of BaseAudioHandler in my application:
class AudioPlayerHandler extends BaseAudioHandler {
#override
Future<void> play() async {
throw Error();
}
}
Then when I call this function from an event handler:
void onPlayButtonTap() {
try {
audioPlayerHandler.play();
} catch (error) {
// Error is not caught, but in the console I see unhandled error message.
print(error.toString())
}
}
It doesn't catch the error thrown within the method.
Of course the example this way doesn't make sense, but I've run into this problem when trying to load an invalid url which i could not handle in 'regular' way.
[VERBOSE-2:dart_vm_initializer.cc(41)] Unhandled Exception: Instance of 'Error'
#0 AudioPlayerHandler.play (package:audio_service_example/main.dart:197:5)
#1 MainScreen._button.<anonymous closure> (package:audio_service_example/main.dart:145:22)
#2 _InkResponseState.handleTap (package:flutter/src/material/ink_well.dart:1072:21)
#3 GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:253:24)
#4 TapGestureRecognizer.handleTapUp (package:flutter/src/gestures/tap.dart:627:11)
#5 BaseTapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:306:5)
#6 BaseTapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:239:7)
#7 PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:615:9)
#8 PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:98:12)
#9 PointerRouter._dispatchEventToRoutes.<anonymous closure> (package:flutter/src/gestures/pointer_ro<…>
I expected to be able to use a try-catch block to handle the error.
I can handle the error inside the audiohandler implementation and let's say I can propagate a custom event that tells the user of the handler that an error occured, but that solution seems to be a bit clumsy.
I'm also not sure if this is a dart programming language quirk unknown to me or an implementation problem? Tried to step through with debugger but did not find anything meaningful.
Could you please help me how this error handling should work?
Thanks you in advance!
This concerns the Dart language.
Because you defined play as an async method, play doesn't actually throw an error. It returns a future which evaluates to an error. If you await that future, you'll be able to catch the error:
try {
await audioPlayerHandler.play();
I am using pdf lib to generate pdf and I want to add a text in pdf coming from the API, the text can be very long like 3,4 pages or more. Below is my code.
List<pw.Widget> widgets = [];
widgets.add(pw.Text(provider.getExtractedText));
final pdf = pw.Document();
pdf.addPage(
pw.MultiPage(
build: (pw.Context context) {
return [
pw.Wrap(
children: widgets
)
];
},
),
);
but i am getting the following exception.
E/flutter (19405): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: Exception: This widget created more than 20 pages. This may be an issue in the widget or the document. See https://pub.dev/documentation/pdf/latest/widgets/MultiPage-class.html
E/flutter (19405): #0 MultiPage.generate.<anonymous closure> (package:pdf/src/widgets/multi_page.dart:251:11)
E/flutter (19405): #1 MultiPage.generate (package:pdf/src/widgets/multi_page.dart:255:8)
E/flutter (19405): #2 Document.addPage (package:pdf/src/widgets/document.dart:118:10)
E/flutter (19405): #3 _DocumentConversionScreenState.saveFile (package:speak_and_translate/screens/document_conversion_screen.dart:215:11)
E/flutter (19405): <asynchronous suspension>
E/flutter (19405):
Your stacktrace gives you file and line number - so go and look there:
// Detect too big widgets
if (sameCount++ > maxPages) {
throw Exception(
'This widget created more than $maxPages pages. This may be an issue in the widget or the document. See https://pub.dev/documentation/pdf/latest/widgets/MultiPage-class.html');
}
As you see, it compares to maxPages. Where is that set? Check line 152:
this.maxPages = 20,
So, change that default to a sensible number for your application:
pw.MultiPage(
maxPages: 40, // <- add max pages here
build: (pw.Context context) {
I am getting the following error Unhandled Exception: Null check operator and I am not sure if it is something wrong in my code or the library I am using. I am trying to test the livequery of the parse_server_sdk used by back4app because I require sending and receiving images in Realtime. Here is the relevant code:
import 'dart:io';
import 'package:filepicker_windows/filepicker_windows.dart';
import 'package:flutter/material.dart';
import 'package:parse_server_sdk_flutter/parse_server_sdk.dart';
void main() async {
final keyApplicationId = 'EPARW6nRAAyp5uehoDE7rBEby4wtehcZf9EayykS';
final keyClientKey = 'fDaL2DjyC9YdwCwZ4RB5c5vhACROaMOO1EjjL4Zn';
final keyParseServerUrl = 'https://parseapi.back4app.com';
final LIVE_QUERY_URL = 'wss://samuraichat.b4a.io';
await Parse().initialize(keyApplicationId, keyParseServerUrl,
clientKey: keyClientKey,
autoSendSessionId: true,
liveQueryUrl: LIVE_QUERY_URL,
coreStore: CoreStoreMemoryImp());
final LiveQuery liveQuery = LiveQuery();
QueryBuilder<ParseObject> query =
QueryBuilder<ParseObject>(ParseObject('FirstClass'))
..whereEqualTo('chatId', 1);
Subscription subscription = await liveQuery.client.subscribe(query);
subscription.on(LiveQueryEvent.create, (value) {
print('*** CREATE ***: ${DateTime.now().toString()}\n $value ');
print((value as ParseObject).objectId);
print((value as ParseObject).get('message'));
});
runApp(MyApp());
}
Here is the error stack:
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: Null check operator used on a null value
#0 MethodChannel.binaryMessenger (package:flutter/src/services/platform_channel.dart:142:86)
#1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:148:36)
#2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:331:12)
#3 MethodChannelConnectivity.checkConnectivity (package:connectivity_platform_interface/src/method_channel_connectivity.dart:41:29)
#4 Connectivity.checkConnectivity (package:connectivity/connectivity.dart:46:22)
#5 Parse.checkConnectivity (package:parse_server_sdk_flutter/parse_server_sdk.dart:106:34)
#6 new LiveQueryReconnectingController (package:parse_server_sdk/src/network/parse_live_query.dart:45:28)
#7 new LiveQueryClient._internal (package:parse_server_sdk/src/network/parse_live_query.dart:146:30)
#8 LiveQueryClient._getInstance (package:parse_server_sdk/src/network/parse_live_query.dart:153:35)
#9 new LiveQuery (package:parse_server_sdk/src/network/parse_live_query.dart:416:30)
#10 main (package:chat_app/main.dart:18:37)
<asynchronous suspension>
Thanks.
Try to clean your app cache:
flutter clean
This bug should be fixed with this PR.
You use the current nullsafety branch by overriding the dependency in your pubspec.yaml:
dependency_overrides:
parse_server_sdk_flutter:
git:
url: https://github.com/parse-community/Parse-SDK-Flutter.git
ref: nullsafety
path: packages/flutter
parse_server_sdk:
git:
url: https://github.com/parse-community/Parse-SDK-Flutter.git
ref: nullsafety
path: packages/dart
I have a basic flutter project running on android where when the application starts, I write an executable bundled in my assets.
static String appInternalPath = '/data/data/com.maksimdan.face_merger';
void writeExecutable() async {
var executablePath = join(appInternalPath, 'main');
if (await File(executablePath).exists()) {
File(executablePath).delete();
print('deleted old executable');
} else {
print('not executable exists');
}
ByteData data = await rootBundle.load('lib/py/dist/main');
List<int> bytes =
data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
await File(executablePath).writeAsBytes(bytes);
print('wrote new executable');
}
Sometime later in my code I try to run it.
void invokeExecutable() async {
String executablePath = join(appInternalPath, 'main');
Process.run('chmod', ['u+x', executablePath]).then((ProcessResult results) {
Process.run(executablePath, []).then((ProcessResult results) {
print(results.stdout);
});
});
}
But obtain a permission denied error.
E/flutter (31825): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)] Unhandled Exception: ProcessException: Permission denied
E/flutter (31825): Command: /data/data/com.maksimdan.flutter_general/main
E/flutter (31825): #0 _ProcessImpl._start (dart:io-patch/process_patch.dart:390:33)
E/flutter (31825): #1 Process.start (dart:io-patch/process_patch.dart:36:20)
E/flutter (31825): #2 _runNonInteractiveProcess (dart:io-patch/process_patch.dart:565:18)
E/flutter (31825): #3 Process.run (dart:io-patch/process_patch.dart:47:12)
E/flutter (31825): #4 _MyHomePageState.invokeExecutable.<anonymous closure> (package:flutter_general/main.dart:51:15)
E/flutter (31825): #5 _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter (31825): #6 _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter (31825): <asynchronous suspension>
I've also tried:
Process.run('/system/bin/chmod', ['744', path]).then((ProcessResult results) {
print('shell1 complete');
Process.run(path, []).then((ProcessResult results) {
print('shell2 complete');
print(results.stdout);
});
});
My executable:
// 'Hello World!' program
#include <iostream>
int main()
{
std::cout << "Hello World!" << std::endl;
return 0;
}
>> g++ main.cc -o main
Is there a way to run your own executables in flutter with the proper permissions? On native android, there is an option to file.setExecutable(true); using this strategy. (Hosting an executable within Android application)
Or will I have to experiment with method channels?
pubspec.yml
name: face_merger
description: A new Flutter project.
version: 1.0.0+1
environment:
sdk: ">=2.1.0 <3.0.0"
dependencies:
flutter:
sdk: flutter
sqflite: ^1.3.0+2
process_run: ^0.10.10+1
cupertino_icons: ^0.1.3
dev_dependencies:
flutter_test:
sdk: flutter
flutter:
uses-material-design: true
assets:
- lib/py/dist/main
I also verified that the file was written to the internal memory of on the device that I expected it to be written to using android studio's device explore.
Besides the writable permission you need to have readable permission in your app.
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.xxx.yyy">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
...
You need to put the .db file extension at the end of the database name (Assuming DB_DIR is for a database). var path = join(DB_DIR, 'main.db');
Then I think you may want to use path_provider package and use
Directory documentsDirectory = await getApplicationDocumentsDirectory();
for the directory where you are accessing the database.
pubspec.yaml
flutter:
uses-material-design: true
assets:
- assets/Images/1.png
- assets/Images/MP3.mp3
Test.dart
Widget localAsset() {
return _tab([
Text("Click to play"),
_btn('Play', () => audioCache.play('assets\Images\MP3.mp3')),
]);
}
I am new to flutter, for my applications i want play two sounds mode(background sound ,button action sound), after referred from flutter package i have changed code like as above , when i used this widget in my material,i am getting below error,
E/flutter ( 2750): [ERROR:flutter/shell/common/shell.cc(181)] Dart Error: Unhandled exception:
E/flutter ( 2750): Unable to load asset: assets/assetsImagesMP3.mp3
E/flutter ( 2750): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:221:7)
Backslash are Windows-specific. Use slashes instead. Android is Unix-based and so is iOS
audioCache.play('assets/Images/MP3.mp3')