Data Model & HTTP

1. Get to a Clean Slate

All Flutter apps start with main.dart. Get rid of all the Counter app stuff, and you'll end up with this:

  1. // main.dart
  2. import 'package:flutter/material.dart';
  3. void main() => runApp(MyApp());
  4. class MyApp extends StatelessWidget {
  5. @override
  6. Widget build(BuildContext context) {
  7. /// MaterialApp is the base Widget for your Flutter Application
  8. /// Gives us access to routing, context, and meta info functionality.
  9. return MaterialApp(
  10. title: 'We Rate Dogs',
  11. // Make all our text default to white
  12. // and backgrounds default to dark
  13. theme: ThemeData(brightness: Brightness.dark),
  14. home: MyHomePage(title: 'We Rate Dogs'),
  15. );
  16. }
  17. }
  18. class MyHomePage extends StatefulWidget {
  19. MyHomePage({Key key, this.title}) : super(key: key);
  20. final String title;
  21. @override
  22. _MyHomePageState createState() => _MyHomePageState();
  23. }
  24. class _MyHomePageState extends State<MyHomePage> {
  25. @override
  26. Widget build(BuildContext context) {
  27. /// Scaffold is the base for a page.
  28. /// It gives an AppBar for the top,
  29. /// Space for the main body, bottom navigation, and more.
  30. return Scaffold(
  31. /// App bar has a ton of functionality, but for now lets
  32. /// just give it a color and a title.
  33. appBar: AppBar(
  34. /// Access this widgets properties with 'widget'
  35. title: Text(widget.title),
  36. backgroundColor: Colors.black87,
  37. ),
  38. /// Container is a convenience widget that lets us style it's
  39. /// children. It doesn't take up any space itself, so it
  40. /// can be used as a placeholder in your code.
  41. body: Container(),
  42. );
  43. }
  44. }

2. Create A Dog Model Class

We'll create a plain Dart class called Dog for our data model.

First, create a new file called dog_model.dart in the lib directory.

  1. - lib
  2. -dog_model.dart
  3. -main.dart

In that file, we'll just create super basic class with a couple properties:

  1. class Dog {
  2. final String name;
  3. final String location;
  4. final String description;
  5. String imageUrl;
  6. // All dogs start out at 10, because they're good dogs.
  7. int rating = 10;
  8. Dog(this.name, this.location, this.description);
  9. }

3. Get Dog Pics

This is our one slight detour. We're going to use a super simple API to generate the dog images. This API doesn't require an API key or anything.

You can find it at dog.ceo. All it does is give us random images of dogs.

In your Dog class, add this method:

  1. // dog_model.dart
  2. Future getImageUrl() async {
  3. // Null check so our app isn't doing extra work.
  4. // If there's already an image, we don't need to get one.
  5. if (imageUrl != null) {
  6. return;
  7. }
  8. // This is how http calls are done in flutter:
  9. HttpClient http = HttpClient();
  10. try {
  11. // Use darts Uri builder
  12. var uri = Uri.http('dog.ceo', '/api/breeds/image/random');
  13. var request = await http.getUrl(uri);
  14. var response = await request.close();
  15. var responseBody = await response.transform(utf8.decoder).join();
  16. // The dog.ceo API returns a JSON object with a property
  17. // called 'message', which actually is the URL.
  18. imageUrl = json.decode(responseBody)['message'];
  19. } catch (exception) {
  20. print(exception);
  21. }
  22. }

NB: This will also require the import of two dart packages:

  1. import 'dart:convert';
  2. import 'dart:io';

4. Create some sample data with the new Dog class.

In main.dart let's create a handful of dogs so we have something to work with.

First import dog_model.dart:

  1. // main.dart
  2. import 'package:flutter/material.dart';
  3. import 'dog_model.dart';

Then add some doggos:

  1. // main.dart in the State class
  2. class _MyHomePageState extends State<MyHomePage> {
  3. List<Dog> initialDoggos = []
  4. ..add(Dog('Ruby', 'Portland, OR, USA',
  5. 'Ruby is a very good girl. Yes: Fetch, loungin\'. No: Dogs who get on furniture.'))
  6. ..add(Dog('Rex', 'Seattle, WA, USA', 'Best in Show 1999'))
  7. ..add(Dog('Rod Stewart', 'Prague, CZ',
  8. 'Star good boy on international snooze team.'))
  9. ..add(Dog('Herbert', 'Dallas, TX, USA', 'A Very Good Boy'))
  10. ..add(Dog('Buddy', 'North Pole, Earth', 'Self proclaimed human lover.'));
  11. }