Flutter Unhandled Exception: Null check operator used on a null value - flutter

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

Related

How to unzip files to device memory in flutter

I was able to download file in zip format from remote server, but when unzip the file containing videos, I got error like this
E/flutter (11680): [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: FileSystemException: Creation failed, path = 'out' (OS Error: Read-only file system, errno = 30)
E/flutter (11680): #0 _Directory.createSync (dart:io/directory_impl.dart:133:7)
E/flutter (11680): #1 extractArchiveToDisk
package:archive/…/io/extract_archive_to_disk.dart:21
E/flutter (11680): #2 ZipService.unzipSigns
package:gsl_distionary/services/zip_service.dart:13
E/flutter (11680): <asynchronous suspension>
Below is my code to unzip file using archive package:
static Future unzipSigns(String fileName) async {
final dir = await getApplicationSupportDirectory();
final bool isZippedFile = await File("${dir.path}/$fileName").exists();
if (isZippedFile) {
final inputStream = InputFileStream("${dir.path}/$fileName");
final archive = ZipDecoder().decodeBuffer(inputStream);
extractArchiveToDisk(archive, 'out');
}
}
What did I miss?

The method 'containsKey' was called on null flutter

Before, my integration test works. After I pull an update of another developer my integration test fails with the following error:
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following NoSuchMethodError was thrown running a test:
The method 'containsKey' was called on null.
Receiver: null
Tried calling: containsKey("serverStatus")
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:38:5)
#1 _IndexState._referAFriendEnabled (package:limitless/pages/index.dart:1390:15)
Transition { currentState: HomeInitial(), event: FetchHomeCarousels(), nextState: HomeInitial() }
Transition { currentState: InitialInboxState(), event: InboxFetch(), nextState: InboxFetchingData() }
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test (but after the test had completed):
'package:flutter_test/src/binding.dart': Failed assertion: line 1558 pos 12: 'inTest': is not true.
When the exception was thrown, this was the stack:
#2 LiveTestWidgetsFlutterBinding.pump (package:flutter_test/src/binding.dart:1558:12)
#3 WidgetTester.pumpAndSettle.<anonymous closure> (package:flutter_test/src/widget_tester.dart:668:23)
<asynchronous suspension>
<asynchronous suspension>
(elided 3 frames from class _AssertionError and package:stack_trace)
════════════════════════════════════════════════════════════════════════════════════════════════════
03:29 +0 -1: end-to-end test limitless non-transactional test
CustomerStart { }
Transition { currentState: CustomerInitial(), event: CustomerStart { }, nextState: CustomerLoading() }
03:31 +0 -1: Some tests failed.
Running the app works fine. It only fails when running integration test.
This is code snippet about containsKey.
void _referAFriendEnabled() async {
bool referralEnabled = false;
PackageInfo packageInfo = await PackageInfo.fromPlatform();
if (prefs.containsKey('serverStatus')) {
Map appSettings = await AppSharedPref.getServerStatus();
limitlessRepo.appVersion = appSettings["app_version"];
limitlessRepo.storeVersion = appSettings["latest_store_app_version"];
referralEnabled = appSettings["referral_code"];
limitlessRepo.version = packageInfo.version;
} else {
await limitlessRepo.isReferralCodeEnabled();
}
newVersionAvailable();
setState(() {
_isReferralEnabled = referralEnabled;
});
Does anyone has an idea about this? Thank you.

Flutter/Dart get_It singleton locator method failure

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!

Flutter Image Compress Always giving error name.toLowerCase called on null

This is the code I am using.
I have checked it with different file format but still showing the same error, i have checked the "img.path" its showing the path to the image. I don't understand why I am getting an error.
String targetPath;
var result = await FlutterImageCompress.compressAndGetFile(
img.path,
targetPath,
quality: 88,
format: CompressFormat.webp,
);
Error I am getting:
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: The method 'toLowerCase' was called on null.
Receiver: null
Tried calling: toLowerCase()
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 Validator.checkFileNameAndFormat
package:flutter_image_compress/src/validator.dart:19
#2 FlutterImageCompress.compressAndGetFile
package:flutter_image_compress/flutter_image_compress.dart:150
#3 _AddImageState.uploadFile
package:softclaw/…/addpost/addimage.dart:225
#4 _AddImageState.build.<anonymous closure>
package:softclaw/…/addpost/addimage.dart:97
<asynchronous suspension>
targetPath is the one that goes through the checkFileNameAndFormat > toLowerCase, therefore check to ensure this is not null.

How to connect to Localhost?

I'm here new, I'm learning flutter and I need login with this:
POST http://localhost:3000/api/users/session
But I still can't login :( I'm waiting 5 minutes and still there is a loading screen with no effects.
I have try
So I have have made a this api_service with this tutorial made https://www.youtube.com/watch?v=_Kw4BfNX1-4
here is my api_service.dart
import 'package:http/http.dart' as http;
import 'dart:convert';
import '../model/login_model.dart';
class APIService {
Future<LoginResponseModel>
login(LoginRequestModel requestModel) async {
String url = "http://localhost:3000/api/users/session";
final response = await http.post(url, body: requestModel.toJson());
if (response.statusCode == 200 || response.statusCode == 400) {
return LoginResponseModel.fromJson(
json.decode(response.body),
);
} else {
throw Exception('Failed to load data!');
}
}
}
Here is debug console:
E/flutter (10967): [ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: SocketException: OS Error: Connection refused,
errno = 111, address = localhost, port = 58856 E/flutter (10967):
I'm try with this page:
https://medium.com/#podcoder/connecting-flutter-application-to-localhost-a1022df63130
I change String url = "http://localhost:3000/api/users/session"; to
String url = "http://10.0.2.2:3000/api/users/session";
in my debug console i have completely different messages, but stilll
don't work :(
E/flutter (10967):
[ERROR:flutter/lib/ui/ui_dart_state.cc(186)]
Unhandled Exception: Bad state: Insecure HTTP is not allowed by
platform: http://10.0.2.2:3000/api/users/session
E/flutter (10967): #0 _HttpClient._openUrl
(dart:_http/http_impl.dart:2434:7)
E/flutter (10967): #1 _HttpClient.openUrl
(dart:_http/http_impl.dart:2341:7)
E/flutter (10967): #2 IOClient.send
package:http/src/io_client.dart:31
(...) to #28 and the last ist E/flutter (10967):
Fix for the Error Unhandled Exception: Bad state: Insecure HTTP is not allowed by platform
Flutter terms http as an insecure source Therefore you should either use https or set android:usesCleartextTraffic to true in AndroidManifest
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name="io.flutter.app.FlutterApplication"
android:label="receipt"
android:usesCleartextTraffic="true" // Add this line
android:icon="#mipmap/ic_launcher">