Skip to content

Instantly share code, notes, and snippets.

@tdewin
Last active August 9, 2023 09:49
Show Gist options
  • Select an option

  • Save tdewin/c4131a613505627fc4cd7e6d9dd1314e to your computer and use it in GitHub Desktop.

Select an option

Save tdewin/c4131a613505627fc4cd7e6d9dd1314e to your computer and use it in GitHub Desktop.
Get a github gist with dart (flutter)
import 'dart:convert';
import 'package:http/http.dart' as http;
class GistFile {
String name;
String rawurl;
String _content = "";
bool truncated;
GistFile(this.name, this.rawurl, this.truncated);
void setContent(content) {
_content = content;
}
Future<String> getContent() async {
String fcontent = _content;
if (truncated) {
final response = await http.get(Uri.parse(rawurl));
if (response.statusCode == 200) {
fcontent = response.body;
truncated = false;
} else {
throw Exception('Failed to get raw file ${rawurl} (http ${response.statusCode})');
}
}
return fcontent;
}
}
class Gist {
late String id;
late String description;
late DateTime createdAt;
late DateTime updatedAt;
late String ownerLogin;
late int ownerId;
late List<GistFile> files;
Gist.fromJson(Map json) {
id = json['id'];
description = json['description'];
createdAt = DateTime.parse(json["created_at"]);
updatedAt = DateTime.parse(json["updated_at"]);
ownerId = json['owner']['id'];
ownerLogin = json['owner']['login'];
files = [];
var fmap = json['files'];
var ftype = "YAML";
fmap.keys.forEach((k) {
if (fmap[k]["language"] == ftype) {
GistFile gistFile = GistFile(fmap[k]["filename"],
fmap[k]["raw_url"],
fmap[k]["truncated"],
);
if (!fmap[k]["truncated"]) {
gistFile.setContent(fmap[k]["content"]);
}
files.add(gistFile);
}
});
}
}
Future<Gist> fetchGist(id) async {
final response = await http
.get(Uri.parse("https://api.github.com/gists/${id}"));
if (response.statusCode == 200) {
return Gist.fromJson(jsonDecode(response.body));
} else {
throw Exception('Failed to load gist ${id} (http ${response.statusCode})');
}
}
void main() {
String id = "cf24237b13eb9584738247fc43a5addc";
Future<Gist> fg = fetchGist(id);
fg.then((g) {
print(g.description);
print(g.createdAt);
print(g.updatedAt);
print(g.ownerId);
print(g.ownerLogin);
g.files.forEach((f) {
print(f.name);
print(f.rawurl);
f.getContent().then((c) { print(c); });
});
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment