-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Create finding-and-converting-json-values-in-dart.dart
- Loading branch information
Showing
1 changed file
with
55 additions
and
0 deletions.
There are no files selected for viewing
55 changes: 55 additions & 0 deletions
55
...inding-and-converting-json-values-in-dart/finding-and-converting-json-values-in-dart.dart
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// π¦ Twitter https://twitter.com/vandadnp | ||
// π΅ LinkedIn https://linkedin.com/in/vandadnp | ||
// π₯ YouTube https://youtube.com/c/vandadnp | ||
// π Free Flutter Course https://linktr.ee/vandadnp | ||
// π¦ 11+ Hours Bloc Course https://youtu.be/Mn254cnduOY | ||
// πΆ 7+ Hours MobX Course https://youtu.be/7Od55PBxYkI | ||
// π¦ 8+ Hours RxSwift Coursde https://youtu.be/xBFWMYmm9ro | ||
// π€ Want to support my work? https://buymeacoffee.com/vandad | ||
|
||
import 'dart:developer' as devtools show log; | ||
|
||
extension Log on Object? { | ||
void log() => | ||
devtools.log(this?.toString() ?? '\x1b[101m\x1b[30mNULL\x1b[0m'); | ||
} | ||
|
||
extension Find<K, V, R> on Map<K, V> { | ||
R? find<T>( | ||
K key, | ||
R? Function(T value) cast, | ||
) { | ||
final value = this[key]; | ||
if (value != null && value is T) { | ||
return cast(value as T); | ||
} else { | ||
return null; | ||
} | ||
} | ||
} | ||
|
||
const json = { | ||
'name': 'Foo Bar', | ||
'age': 20, | ||
}; | ||
|
||
void testIt() { | ||
// get the age | ||
final String? ageAsString = json.find( | ||
'age', | ||
(int value) => 'Your age is $value', | ||
); | ||
ageAsString.log(); | ||
// force get the name using ! operator | ||
final String helloName = json.find( | ||
'name', | ||
(String name) => 'Hello, $name', | ||
)!; | ||
helloName.log(); | ||
// non-existent key | ||
final String? address = json.find( | ||
'address', | ||
(String address) => 'You live at $address', | ||
); | ||
address.log(); | ||
} |