Last active
July 28, 2023 16:01
-
-
Save eernstg/9c68ed5a11867e6e2085816f14a483bf to your computer and use it in GitHub Desktop.
A variant of the 'Dart decoding using dart:convert' example using extension types
This file contains hidden or 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
import 'package:http/http.dart' as http; | |
import 'dart:convert'; | |
main() async { | |
const pubUrl = "https://pub.dartlang.org/api/packages/protobuf"; | |
var response = await http.get(Uri.parse(Uri.encodeFull(pubUrl))); | |
if (response.statusCode == 200) { | |
PkgInfo info = PkgInfo(json.decode(response.body)); | |
print('Package ${info.name}, v ${info.latest.pubspec.version}'); | |
} else { | |
throw Exception('Failed to load package info'); | |
} | |
} | |
extension type PkgInfo(Map<String, dynamic> json) { | |
String get name => json['name']!; | |
PkgVersion get latest => PkgVersion(json['latest']!); | |
String get version => json['version']!; | |
} | |
extension type PkgVersion(Map<String, dynamic> json) { | |
String get archiveUrl => json['archive_url']!; | |
PkgPubspec get pubspec => PkgPubspec(json['pubspec']!); | |
} | |
extension type PkgPubspec(Map<String, dynamic> json) { | |
String get version => json['version']!; | |
String get name => json['name']!; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
It might be cool to have nested extension members (similar to Kotlin's):
They're a bit weird, though, because they can only be invoked in a context where the current instance of the enclosing type declaration is available implicitly (for instance, inside the body of the declaration of
_Base
), such that there is a way to give meaning to expressions likejson
.But I digress. ;-)