Skip to content

Instantly share code, notes, and snippets.

@eernstg
Created January 30, 2023 19:01
Show Gist options
  • Save eernstg/9b438407f74bd3461003da12eb0115d2 to your computer and use it in GitHub Desktop.
Save eernstg/9b438407f74bd3461003da12eb0115d2 to your computer and use it in GitHub Desktop.
A variant of the 'Dart decoding using dart:convert' example using inline classes
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');
}
}
inline class PkgInfo {
final Map<String, dynamic> json;
PkgInfo(this.json);
String get name => json['name']!;
PkgVersion get latest => PkgVersion(json['latest']!);
String? get version => json['version']!;
}
inline class PkgVersion {
final Map<String, dynamic> json;
PkgVersion(this.json);
String get archiveUrl => json['archive_url']!;
PkgPubspec get pubspec => PkgPubspec(json['pubspec']!);
}
inline class PkgPubspec {
final Map<String, dynamic> json;
PkgPubspec(this.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