Marcos Placona
Marcos Placona
Marcos an experienced Developer Relations leader turned solopreneur, GDE and in ❤️ with Open Source
1 min read

Categories

  • Dart

Dart Gists

I just thought I’d write this simple example that shows how to retrieve your GitHub’s gists with Dart language. The focus on this is to show how to handle Futures and make HTTP requests in Dart.

The code is very simple, and runs as a CLI application. It asks the user for a valid Github login, and tries to fetch the last 30 gist entries for that user.

The main class is as follows:

class Gists{
    // instance variable for user
    String user;
    getGistsForUser(String user){
      this.user = user; 
      var url = "https://api.github.com/users/${this.user}/gists";
      http.get(url)
        .then(_processResults)
        .catchError(_handleError);
    }
      
    _processResults(http.Response jsonString){
      List<String> urls = JSON.decode(jsonString.body);
      urls.forEach((element){
        print(element["html_url"]);
      });
    }
      
    _handleError(Error error){
      print("User ${this.user} not available");
    }
}

As you can see, I do an HTTP get to Github’s API requesting the gists for my user. I then use Futures to make sure my application doesn’t cause blockage while we’re fetching the results via the API. I also do some processing on the results, by parsing the JSON response and printing each of the URL’s.

If the user is invalid, we then display an error message.

Full code with a sample call: