riverpod

A reactive caching and data-binding framework. Riverpod makes working with asynchronous code a breeze.

RAW Doc

1. Project Overview & Quickstart (rrousselGit/riverpod)

File: README.md

[](https://github.com/rrousselGit/riverpod/actions) [](https://codecov.io/gh/rrousselgit/riverpod) [](https://github.com/rrousselgit/riverpod) [](https://opensource.org/licenses/MIT) [](https://discord.gg/GSt793j6eT)
text
<a href="https://www.netlify.com">
  
</a>

A reactive caching and data-binding framework. https://riverpod.dev
Riverpod makes working with asynchronous code a breeze by:

  • Handling errors/loading states by default. No need to manually catch errors
  • Natively supporting advanced scenarios, such as pull-to-refresh
  • Separating the logic from your UI
  • Ensuring your code is testable, scalable and reusable
riverpod
flutter_riverpod
hooks_riverpod

Welcome to Riverpod (anagram of Provider)!

For learning how to use Riverpod, see its documentation:
>>> https://riverpod.dev <<<

Long story short:

  • Define network requests by writing a function annotated with @riverpod:

    dart
    @riverpod
    Future<String> boredSuggestion(Ref ref) async {
      final response = await http.get(
        Uri.https('boredapi.com', '/api/activity'),
      );
      final json = jsonDecode(response.body);
      return json['activity']! as String;
    }
  • Listen to the network request in your UI and gracefully handle loading/error states.

    dart
    class Home extends ConsumerWidget {
      @override
      Widget build(BuildContext context, WidgetRef ref) {
        final boredSuggestion = ref.watch(boredSuggestionProvider);
        // Perform a switch-case on the result to handle loading/error states
        return switch (boredSuggestion) {
          AsyncData(:final value) => Text('data: $value'),
          AsyncError(:final error) => Text('error: $error'),
          _ => const Text('loading'),
        };
      }
    }

Contributing

Contributions are welcome!

Here is a curated list of how you can help:

  • Report bugs and scenarios that are difficult to implement
  • Report parts of the documentation that are unclear
  • Fix typos/grammar mistakes
  • Update the documentation or add examples
  • Implement new features by making a pull-request

Sponsors


File: benchmarks/README.md

A list of benchmarks to measure the different aspects of Riverpod

To run a benchmark, run:

sh
flutter run --release -t lib/some_benchmark.dart

File: examples/counter/README.md

The standard Flutter Counter example built with Riverpod

This uses ProviderScope.


File: examples/marvel/README.md

A Flutter app that displays the list of comics from https://developer.marvel.com/

Goal of this example

This example demonstrates how to:

  • perform HTTP requests
  • handle pagination
  • cancel HTTP requests if the UI stops listening to the response before completion
  • implement a search-bar that has its own independent state.
  • support deep-linking to an item
  • optimize widget rebuilds (only what needs to update does update).

Installation

To run this example, you will need to create a configurations.json placed in the assets folder:

text
example/
  pubspec.yaml
  assets/
    configurations.json  << Where to place the file
  lib/

The content of this file looks like this:

json
{
  "public_key": "1234",
  "private_key": "5678"
}

Where public_key and private_key are obtained from https://developer.marvel.com/account

Since this project uses freezed for code generation, be sure to run the generator with the following command before attempting to build/run the application:

sh
dart run build_runner build -d

File: examples/pub/README.md

Pub

Install needed global packages

bash
cd riverpod
dart pub global activate melos

Build the Example App

Run the code generation

bash
cd examples/pub
flutter pub get
dart run build_runner build -d

Run the Example App

Create and run the android deployable

bash
flutter create . --platforms android
flutter run

File: examples/random_number/README.md

random_number

A random number generator similar to the counter project. It has a single button that generates a random number.

Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter, view our
online documentation, which offers tutorials,
samples, guidance on mobile development, and a full API reference.


File: examples/stackoverflow/README.md

A StackOverflow client implemented using Riverpod and the official StackOverflow API

The example is still in progress

Setup

This example uses code generation.
Before starting the application, you must first start the code generators.

This can be done with:

sh
cd examples/stackoverflow
dart run build_runner build -d

File: examples/todos/README.md

A todo-list built with Riverpod

This showcase slightly more advanced state manipulation, using [Computed].


File: packages/riverpod_sqflite/example/README.md

example

A new Flutter project.

Getting Started

This project is a starting point for a Flutter application.

A few resources to get you started if this is your first Flutter project:

For help getting started with Flutter development, view the
online documentation, which offers tutorials,
samples, guidance on mobile development, and a full API reference.


File: packages/riverpod_sqflite/README.md

[](https://github.com/rrousselGit/riverpod/actions) [](https://codecov.io/gh/rrousselgit/riverpod) [](https://github.com/rrousselgit/riverpod) [](https://opensource.org/licenses/MIT) [](https://discord.gg/GSt793j6eT)
text
<a href="https://www.netlify.com">
  
</a>

Say Hi to Riverpod_sqflite!

This is an official implementation of offline-persistence in Riverpod
using Sqflite.

Usage

First, you need to create a connector to the database. This can be done by creating a storageProvider:

dart
final storageProvider = FutureProvider<JsonSqFliteStorage>((ref) async {
  // Initialize SQFlite. We should share the Storage instance between providers.
  return JsonSqFliteStorage.open(
    join(await getDatabasesPath(), 'riverpod.db'),
  );
});

Then, create a Notifier, mix-in Persistable and then invoke persist inside Notifier.build:

dart
class TodosNotifier extends AsyncNotifier<List<Todo>> {
  @override
  FutureOr<List<Todo>> build() async {
    // We call persist at the start of our `build` method.
    // This will:
    // - Read the DB and update the state with the persisted value the first
    //   time this method executes.
    // - Listen to changes on this provider and write those changes to the DB.
    // We "await" for persist to complete to make sure that the decoding is done
    // before we return the state.
    // If you do not care about the decoded value, don't await the future.
    await persist(
      // We pass our JsonSqFliteStorage instance. No need to "await" the Future.
      // Riverpod will take care of that.
      ref.watch(storageProvider.future),
      // A unique key for this state.
      // No other provider should use the same key.
      key: 'todos',
      // By default, state is cached offline only for 2 days.
      // In this example, we tell Riverpod to cache the state forever.
      options: const StorageOptions(cacheTime: StorageCacheTime.unsafe_forever),
      encode: jsonEncode,
      decode: (json) {
        final decoded = jsonDecode(json) as List;
        return decoded
            .map((e) => Todo.fromJson(e as Map<String, Object?>))
            .toList();
      },
    ).future;

    // If a state is persisted, we return it. Otherwise we return an empty list.
    return state.value ?? [];
  }

  Future<void> add(Todo todo) async {
    // When modifying the state, no need for any extra logic to persist the change.
    // Riverpod will automatically cache the new state and write it to the DB.
    state = AsyncData([...await future, todo]);
  }
}

2. Official Technical Reference & Guides (rrousselGit/website)

[Flutter][]'s website ![Flutter logo][]

Build Status

Issues, bugs, and requests

We welcome contributions and feedback on our website!
Please file a request in our
issue tracker
and we'll take a look.

For simple changes (such as to CSS and text), you probably don't need to
build this site. Often you can make changes using the GitHub UI.

If you want/need to build, read on.

Before you build this site

1. Get the prerequisites

Install the following tools if you don't have them already.

  • bash, the Bourne shell. These instructions assume you're using bash -- setup might not work if you use another shell.
  • nvm, the Node Version Manager.
  • rvm, the Ruby Version Manager.
  • Flutter
  • Dart SDK

IMPORTANT: Follow the installation instructions for each of the tools
carefully. In particular, configure your shell/environment so
that the tools are available in every terminal/command window you create.

2. Clone this repo _and_ its submodules

NOTE: This repo has git submodules, which affects how you clone it.

To clone this repo, follow the instructions given in the
GitHub help on Cloning a repository, and choose one of the following
submodule-cloning techniques:

  • Clone this repo and its submodule at the same, use the
    --recurse-submodules option:
    git clone --recurse-submodules https://github.com/flutter/website.git
  • If you've already cloned this repo without its submodule, then run
    this command from the repo root:
    git submodule update --init --remote

NOTE: At any time during development you can use the submodule command to
refresh submodules:

text
git pull; git submodule update --init --remote

3. Run installation scripts

NOTE: It is safe to (re-)run all of the commands and scripts given below even
if you already have the required packages installed.

Open a bash terminal/command window and execute the following commands:

  1. cd *\*   # change to
    root of this repo
  2. source ./tool/env-set.sh   #
    initialize environment variables; install/use required Node & Ruby version
  3. ./tool/before-install.sh   #
    install core set of required tools
  4. ./tool/install.sh   #
    install everything else needed to build this site

IMPORTANT:

  • Any time you create a new terminal/command window to work on
    this repo, repeat steps 1 and 2 above.
  • If you upgrade Dart then rerun all of the steps above.

Developing

  1. Create a branch.

  2. Make your changes.

  3. Test your changes by serving the site locally.
    Run either one of these commands:

    • ./tool/serve.sh (can also run via npm run start)

    or

    • bundle exec jekyll serve --incremental --watch --livereload --port 4002

      Note: Unless you're editing files under site-shared, you can safely
      ignore ERROR: directory is already being watched messages.
      For details, see #1363.

      Note: The first time you run either one of these commands,
      jekyll takes anywhere between 10 - 20 seconds to generate static
      content inside the _sites directory. If you try to verify the
      site locally but aren't able to see the content right away,
      wait 20 seconds before stopping the
      server or concluding that something is wrong.

  4. Prior to submitting, validate site links:
    ./tool/shared/check-links.sh

TIP: Sometimes Jekyll gets confused and seems to be out-of-sync. (This might
happen, for example, when you pull from master and lots of files have moved.)
To fix Jekyll, stop the serve.sh script and remove the generated site files:
hand, and then restart the serve.sh script:

npm run clean
OR
rm -Rf ./_site/* ./.jekyll*

Next, restart the serve.sh script:

npm run start
OR
./tool/serve.sh

Creating and/or editing DartPad example code

At the time of writing this (10/22/19) most of the code used to create DartPad examples is hosted on GitHub. However, this repo also contains some .dart files responsible for DartPad example code.

DartPad example code in GitHub gists

A typical DartPad example takes the form of an iframe, e.g. within a codelab's markdown file:

markdown

This iframe depends on the following GitHub gist url:

https://gist.github.com/d7b09149ffee2f0535bb0c04d96987f5

For detailed instructions on how to use this approach to DartPad examples, see the DartPad embedding guide.

DartPad example code in this repo - `src/_packages/dartpad_picker`

Some DartPad example code remains in .dart files in this repo, and must be compiled via src/_packages/dartpad_picker/compile.sh. For an example, consult src/_packages/dartpad_picker/web/dartpad_picker_main.dart.

In order to create or change example code using dartpad_picker, you must regenerate the JavaScript:

sh
cd src/_packages/dartpad_picker
  ./compile.sh

Deploy to a staging site

You can deploy your local edits to a personal staging site as follows
(steps 1 and 2 need to be done only once):

  1. In the Firebase Console,
    create your own Firebase project (e.g. 'mit-flutter-staging')

  2. Tell Firebase about that project with the firebase
    use command:

    console
    $ npx firebase use --add
    ? Which project do you want to add? <select the project you created>
    ? What alias do you want to use for this project? (e.g. staging) my-foo
  3. Tell Firebase that you want to deploy to staging:

    console
    $ npx firebase use my-foo
    Now using alias staging (<your project name>)
  4. Tell Firebase to execute deployment of your project:

console
$ npx firebase deploy

Your personal version of the Flutter website is now deployed to Firebase.

Alternatively, you can skip the previous steps and just use the deploy script:

console
$ ./tool/shared/deploy.sh --local my-foo

=== Deploying to '<your project name>'...

i  deploying hosting
i  hosting: preparing _site directory for upload...
✔  hosting: 213 files uploaded successfully
i  starting release process (may take several minutes)...

✔  Deploy complete!

Deploying to the official site

Usually, official site deploys are performed by Travis. In the event that you
need to manually deploy, use the deploy script and the default project:

text
./tool/shared/deploy.sh --local --robots ok default

Writing for flutter.dev

The site-shared repo
contains infrastructure shared by most of our Dart and Flutter websites.
As a result, we've moved some of content of this README to the
docs
directory in the shared repo.

For more information on using/writing for this repo,
refer to the following docs:

Also check out the site-shared
wiki: