How to add elements into ArrayList in HashMap? DART & Flutter - flutter

Looking for an example in dart exactly like this question: How to add element into ArrayList in HashMap
Map<int, List<Message>> user_id_mapped_to_messages_list = new HashMap();
This throws a null insert, what am I missing here?
user_id_mapped_to_messages_list[user_id].add(message_to_current_user);
Error:
I/flutter (11992): ==============================================
I/flutter (11992): Message is going to the logged in user id of: 11
I/flutter (11992): Message details:
I/flutter (11992): sender: Instance of 'User'
I/flutter (11992): time: 2020-05-11 22:28:26
I/flutter (11992): text: Message 2 from John to Joe
I/flutter (11992): message added to chat group
E/flutter (11992): [ERROR:flutter/lib/ui/ui_dart_state.cc(157)] Unhandled Exception: NoSuchMethodError: The method 'add' was called on null.
E/flutter (11992): Receiver: null
E/flutter (11992): Tried calling: add(Instance of 'Message')
E/flutter (11992): #0 Object.noSuchMethod (dart:core-patch/object_patch.dart:53:5)
E/flutter (11992): #1 _myappnameMessagesRecentChatsState.getConversations.<anonymous closure>.<anonymous closure>
(package:myappname_app_androidx/widgets/home/messages/messages_v2/recent_chats.dart:158:83)
No items existed... for loop printing the messages in the array list
user_id_mapped_to_messages_list.forEach((k,v) => print('${k}: ${v}'));

You created user_id_mapped_to_messages_list variable of type Map> but initialised with HashMap because of that you are getting error.
it should be like below.
Map<int, List<Message>> user_id_mapped_to_messages_list = new Map();
Update:
This is happening because when you directly assign or add any value to list when it is not actually initialised, so add following line before a
user_id_mapped_to_messages_list[user_id] = [];
user_id_mapped_to_messages_list[user_id] = [];
if (user_id_mapped_to_messages_list[user_id] == null) {
user_id_mapped_to_messages_list[user_id] = [];
user_id_mapped_to_messages_list[user_id].add(message_to_current_user);
} else {
user_id_mapped_to_messages_list[user_id].add(message_to_current_user);
}

Related

Issue- Flutter plugin : google_maps_webservice^0.0.20-nullsafety.5" "fields" Attribute gives error

I am using this "google_maps_webservice^0.0.20-nullsafety.5" in flutter
Can some one please let me know, what I am doing wrong here
Signature:
Future getDetailsByPlaceId(
String placeId, {
String? sessionToken,
List fields = const [],
String? language,
String? region, }
)
Here is how I am using it
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(
p.placeId.toString(),
fields: ['name'], // Commenting out this line, would make it work, but i need this attribute/property to save cost
language: 'fr',
region:"fr",
);
Issue:
fields: ['name'] => this "fields" attribute keeps failing,
I have seen so many tutorials , all are suggesting the same way,
but still it fails with the below message
E/flutter ( 9854): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: type 'Null' is not a subtype of type 'String' in type cast
E/flutter ( 9854): #0 _$PlaceDetailsFromJson (package:google_maps_webservice/src/places.g.dart:138:31)
E/flutter ( 9854): #1 new PlaceDetails.fromJson (package:google_maps_webservice/src/places.dart:710:7)
E/flutter ( 9854): #2 _$PlacesDetailsResponseFromJson (package:google_maps_webservice/src/places.g.dart:294:26)
E/flutter ( 9854): #3 new PlacesDetailsResponse.fromJson (package:google_maps_webservice/src/places.dart:838:7)
E/flutter ( 9854): #4 GoogleMapsPlaces._decodeDetailsResponse (package:google_maps_webservice/src/places.dart:528:29)
E/flutter ( 9854): #5 GoogleMapsPlaces.getDetailsByPlaceId (package:google_maps_webservice/src/places.dart:126:12)
E/flutter ( 9854):
E/flutter ( 9854): #6 _LocationPickerInitialState.goToPlace (package:myproj/screens/maps/initialOwnerLocationpicker.dart:149:11)
E/flutter ( 9854):
Here is how I am using it
PlacesDetailsResponse detail =
await _places.getDetailsByPlaceId(
p.placeId.toString(),
fields: ['name'], // Commenting out this line, would make it work, but i need this attribute/property to save cost
language: 'fr',
region:"fr",
);

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 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.

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

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

audio_service flutter package does not start

I am trying to use the audio_service package to allow background controls for my podcast playing app. The service does not start. When I call AudioService.start(), nothing is ever returned (I'm awaiting this function and trying to print a statement after this returns, but it never returns. Also, when I first attempt to play an item, it will correctly evaluate AudioService.running to false and then try to start the AudioService (hanging on the start() function). When I hit play a second time, it will evaluate AudioService.running as true (even though the start function never returned) and will then throw this error:
E/flutter ( 8726): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: PlatformException(Attempt to invoke virtual method 'void io.flutter.plugin.common.MethodChannel.invokeMethod(java.lang.String, java.lang.Object, io.flutter.plugin.common.MethodChannel$Result)' on a null object reference, null, null)
E/flutter ( 8726): #0 StandardMethodCodec.decodeEnvelope (package:flutter/src/services/message_codecs.dart:572:7)
E/flutter ( 8726): #1 MethodChannel._invokeMethod (package:flutter/src/services/platform_channel.dart:161:18)
E/flutter ( 8726): <asynchronous suspension>
E/flutter ( 8726): #2 MethodChannel.invokeMethod (package:flutter/src/services/platform_channel.dart:334:12)
E/flutter ( 8726): #3 AudioService.play (package:audio_service/audio_service.dart:895:20)
Here is my code which calls the start function:
if(AudioService.running) {
print('playing audio service: ${AudioService.running}');
AudioService.play();
} else {
MediaItem mediaItem = MediaItem(
id: newPostPod.audioUrl,
title: newPostPod.titleTextString(),
artist: newPostPod.subtitleTextString(),
);
print('starting audio service');
bool started = await AudioService.start(
backgroundTaskEntrypoint: _backgroundTaskEntrypoint,
params: {'mediaItem': mediaItem.toJson()},
);
print('audio service started');
if(AudioService.running) {
print('starting to play via media service');
AudioService.playMediaItem(mediaItem);
} else {
print('Audio Service not yet started: $started');
}
}
The code for the background task entrypoint (which is outside of any other class, as it wasn't working inside a class I had read in another issue that it had to be top-level):
_backgroundTaskEntrypoint() {
AudioServiceBackground.run(() => PlayerTask());
}
Lastly, it doesn't appear any of the code within my onStart in my BackgroundAudioTask is running (as print statements at the top of my onStart are not being run). So I'm not sure what's happening here. It isn't give me a clear error or really any hint of where to start debugging audio_service.
Calling AudioService.connect(); before starting the service will solve the error.
For me AudioService.start() would freeze until I added the WAKE_LOCK and FOREGROUND_SERVICE permissions to the AndroidManifest.xml file per the audio_service README file.