0

Fetch subreddit posts using Dart IO

Function Dart 1 revisions 128 5 months ago 5 months ago
import 'dart:async';
import 'dart:io';
import 'dart:convert';

Future<List<dynamic>> fetchSubreddit(String subreddit, [String section = 'hot']) async {
  Uri uri = Uri.parse('https://www.reddit.com/r/${subreddit}/${section}.json');

  HttpClientRequest request = await new HttpClient().get(uri.host, 80, uri.path);
  HttpClientResponse response = await request.close();
  return jsonDecode(await readResponse(response))['data']['children'];
}

// https://codebottle.io/s/6dfa56f377
Future<String> readResponse(HttpClientResponse response) {
  var completer = new Completer();
  var contents = new StringBuffer();
  response.transform(UTF8.decoder).listen((String data) {
    contents.write(data);
  }, onDone: () => completer.complete(contents.toString()));
  return completer.future;
}

This function returns a Future that eventually resolves to a List of JSON objects. Each JSON object represents a Reddit POST. Here's a quick example usage:

List<dynamic> stuff = await fetchSubreddit('dartlang');
// or
List<dynamic> stuff = await fetchSubreddit('dartlang', 'new');

print(stuff[0]['data']['title']);