Skip to content

Instantly share code, notes, and snippets.

@KDCinfo
Created September 16, 2021 06:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save KDCinfo/f329655032b7b189dfdd9e82e97010e3 to your computer and use it in GitHub Desktop.
Save KDCinfo/f329655032b7b189dfdd9e82e97010e3 to your computer and use it in GitHub Desktop.
Dart (/Flutter): A null safe approach to convert a dynamic List inside a Map into a List of Strings.
void main() {
/// I got the below working as a null safe approach used to
/// convert a `dynamic` List inside a Map, such as one received
/// and json.decoded from an API endpoint, into a List of `String`s.
///
/// If anyone knows if anything is incorrect or can be done better, please comment.
/// Always looking to learn proper methodologies and better approaches.
/// Two scenarios: A key exists in a Map, or it doesn't (is null).
///
/// Map<String, List<dynamic>> _statusObj = {'message': ['Hello!']};
/// Map<String, List<dynamic>> _statusObj = {};
/// Test #1: A key exists.
///
Map<String, List<dynamic>> _statusObj = {'message': ['Hello!']};
List<String> _alertMsgStrA = List<String>.from(_statusObj["message"]?.toList() ?? <String>[]);
// Works --- [Hello!] 1
List<String> _alertMsgStrB = List<String>.from(_statusObj["message"]?.toList() ?? <String>['Missing message.']);
// Works --- [Hello!] 1
List<dynamic> _alertMsgStrC = _statusObj["message"]?.toList() ?? <String>['Missing message.'];
// Works, but List is still dynamic.
// List<String> _alertMsgStr = List<String>.from(_statusObj["message"]?.toList() as List<String>? ?? <String>['Missing message.']);
// List<String> _alertMsgStr = _statusObj["message"]?.toList() as List<String>? ?? <String>['Missing message.'];
// Uncaught Error: TypeError: Instance of 'JSArray<dynamic>': type 'JSArray<dynamic>' is not a subtype of type 'List<String>?'
print(_alertMsgStrA); // // [Hello!]
print(_alertMsgStrA.length); // 1
print(_alertMsgStrB); // // [Hello!]
print(_alertMsgStrB.length); // 1
print(_alertMsgStrC); // // [Hello!]
print(_alertMsgStrC.length); // 1
/// Test #2: No key exists.
///
Map<String, List<dynamic>> _statusObj2 = {};
List<String> _alertMsgStr2A = List<String>.from(_statusObj2["message"]?.toList() ?? <String>['Missing message.']);
// Works --- [Missing message.] 1
List<String> _alertMsgStr2B = List<String>.from(_statusObj2["message"]?.toList() ?? <String>[]);
// Works --- [] 0
// List<String> _alertMsgStr2C = _statusObj2["message"]?.toList() as List<String>? ?? <String>['Missing message.'];
// This only works when key is null.
print(_alertMsgStr2A); // // [Missing message.]
print(_alertMsgStr2A.length); // 1
print(_alertMsgStr2B); // // []
print(_alertMsgStr2B.length); // 0
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment