Fetching tasks

Before you continue:

Make sure you went through the Quickstart and got Flutter Data up and running!

Also, you can check out the full source code for this tutorial at https://github.com/flutterdata/tutorial

We now have access to our Repository<Task> through ref.tasks, with an API base URL set to https://my-json-server.typicode.com/flutterdata/demo/.

Inspecting the /tasks endpoint we see:

[
  {
    "id": 1,
    "title": "Laundry ๐Ÿงบ",
    "completed": false,
    "userId": 1
  },
  {
    "id": 2,
    "title": "Groceries ๐Ÿ›’",
    "completed": true,
    "userId": 1
  },
  {
    "id": 3,
    "title": "Reservation at Malloys",
    "completed": true,
    "userId": 1
  },
  // ...
]

To bring these tasks into our app we’ll use the watchAll method. (It internally makes a remote findAll call to /tasks and keeps watching local storage for any further changes in these models.)

class TasksApp extends HookConsumerWidget {
  @override
  Widget build(BuildContext context, WidgetRef ref) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: ref.watch(repositoryInitializerProvider).when(
            error: (error, _) => Text(error.toString()),
            loading: () => const CircularProgressIndicator(),
            data: (_) {
              final state = ref.tasks.watchAll();
              if (state.isLoading) {
                return CircularProgressIndicator();
              }
              return ListView(
                children: [
                  for (final task in state.model) Text(task.title),
                ],
              );
            },
          ),
        ),
      ),
      debugShowCheckedModeBanner: false,
    );
  }
}

Bam ๐Ÿ’ฅ!

Whoa, how did that happen?

Understanding the magic โœจ

How exactly does Flutter Data resolve the http://base.url/tasks URL?

Flutter Data adapters define functions and getters such as urlForFindAll, baseUrl and type among many others.

In this case, findAll will look up information in baseUrl and urlForFindAll (which defaults to type, and type defaults to tasks).

Result? http://base.url/tasks.

And, how exactly does Flutter Data instantiate Task models?

Flutter Data ships with a built-in serializer/deserializer for classic JSON. It means that the default serialized form of a Task instance looks like:

{
  "id": 1,
  "title": "delectus aut autem",
  "completed": false
}

Of course, this too can be overridden like the JSON API Adapter does.

For more information see the Repository docs.

NEXT: Marking tasks as done