Firebase SQL Connect client SDKs let you call your server-side queries and
mutations directly from a Firebase app. You generate a custom client SDK in
parallel as you design the schemas, queries and mutations you deploy to your
SQL Connect service. Then, you integrate methods from this SDK into
your client logic.

As we've mentioned elsewhere, it's important to note that SQL Connect
queries and mutations are not submitted by client code and executed on the
server. Instead, when deployed, SQL Connect operations are stored on
the server like Cloud Functions. This means you need to deploy corresponding
client-side changes to avoid breaking existing users (for example, on older app
versions).

That's why SQL Connect provides you with a developer environment and
tooling that lets you prototype your server-deployed schemas, queries and mutations.
It also generates client-side SDKs automatically, while you prototype.

When you've iterated updates to your service and client apps, both server- and
client-side updates are ready to deploy.

## What is the client development workflow?

If you followed the [Get started](https://firebase.google.com/docs/sql-connect/quickstart.md.txt), you were
introduced to the overall development flow for SQL Connect. In this
guide, you'll find more detailed information about generating Flutter SDKs from
your schema and working with client queries and mutations.

To summarize, to use generated Flutter SDKs in your client apps, you'll follow
these prerequisite steps:

1. Add Firebase to your [Flutter](https://firebase.google.com/docs/flutter/setup.md.txt) app.
2. Install the flutterfire CLI `dart pub global activate flutterfire_cli`.
3. Run `flutterfire configure`.

Then:

1. Develop your app schema.
2. Set up SDK generation:

   - With the **Add SDK to app** button in our SQL Connect VS Code extension
   - By [updating your `connector.yaml`](https://firebase.google.com/docs/sql-connect/flutter-sdk.md.txt#generate-flutter).
3. [Initialize your client code and import libraries](https://firebase.google.com/docs/sql-connect/flutter-sdk.md.txt#set-client).

4. [Implement calls to queries](https://firebase.google.com/docs/sql-connect/flutter-sdk.md.txt#using-queries) and [mutations](https://firebase.google.com/docs/sql-connect/flutter-sdk.md.txt#using-mutations).

5. [Set up and use the SQL Connect emulator](https://firebase.google.com/docs/sql-connect/flutter-sdk.md.txt#prototype-and) and
   iterate.

## Generate your Flutter SDK

Use the Firebase CLI to set up SQL Connect generated SDKs in your apps.
The `init` command should detect all apps in the current folder and install
generated SDKs automatically.

```sql
firebase init dataconnect:sdk
```

### Update SDKs while prototyping

If you have SQL Connect VS Code extension installed, it will always keep generated
SDKs up to date.

If you don't use SQL Connect VS Code extension, you can use Firebase CLI
to keep generated SDKs up to date.

```bash
firebase dataconnect:sdk:generate --watch
```

### Generate SDKs in build pipelines

You can use the Firebase CLI to generate SQL Connect SDKs in CI/CD build processes.

```bash
firebase dataconnect:sdk:generate
```

## Set up client code

### Initialize your SQL Connect app

First, initialize your app using the
[standard Firebase setup instructions](https://firebase.google.com/docs/flutter/setup.md.txt).

Then, install the SQL Connect plugin:

```bash
flutter pub add firebase_data_connect
```

### Initialize the SQL Connect Flutter SDK

Initialize your SQL Connect instance using the information you
used to set up SQL Connect. Find this information in the
**Databases \& Storage** \>
[**SQL Connect** page](https://console.firebase.google.com/project/_/dataconnect)
of the Firebase console.

#### Import libraries

There are two sets of imports needed to initialize your client code, general
SQL Connect imports and specific, generated SDK imports.

```dart
// general imports
import 'package:firebase_data_connect/firebase_data_connect.dart';

// generated queries and mutations from SDK
import 'generated/movies.dart';
```

## Use queries on the client side

The generated code will already come with predefined Query Refs. All you need
to do is import and call `execute` on them.

```dart
import 'generated/movies.dart';

await MoviesConnector.instance.listMovies().execute();
```

### Call SDK query methods

Here's an example using these action shortcut functions:

```dart
import 'generated/movies.dart';

function onBtnClick() {
  // This will call the generated Dart from the CLI and then make an HTTP request to the server.
  MoviesConnector.instance.listMovies().execute().then(data => showInUI(data)); // == MoviesConnector.instance.listMovies().ref().execute();
}
```

#### Optional fields

Some queries may have optional fields. In these cases, the Flutter SDK exposes
a builder method, and will have to be set separately.

For example, the field `rating` is optional when calling `createMovie`, so you
need to provide it in the builder function.

```dart
await MoviesConnector.instance.createMovie( title: 'Empire Strikes Back', releaseYear: 1980, genre: 'Sci-Fi').rating(5).execute();
```

### Subscribe to changes

See [Get real-time updates from SQL Connect](https://firebase.google.com/docs/sql-connect/realtime.md.txt).

### Handle changes to enumeration fields

An app's schema can [contain enumerations](https://firebase.google.com/docs/sql-connect/schemas-guide.md.txt#enumeration-fields),
which can be accessed by your [GraphQL queries](https://firebase.google.com/docs/sql-connect/queries-guide.md.txt#query-enumerations).

As an app's design changes, you may add new enum supported values. For example,
imagine that later in your application's lifecycle you decide to add a
FULLSCREEN value to the `AspectRatio` enum.

In the SQL Connect workflow, you can use local development tooling to
update your queries and SDKs.

However, before you release an updated version of your clients, older deployed
clients may break.

#### Example resilient implementation

The generated SDK forces handling of unknown values. That is, client code must
unwrap the `EnumValue` object into either `Known` or `Unknown`.

```dart
final result = await MoviesConnector.instance.listMovies().execute();

if (result.data != null && result.data!.isNotEmpty) {
  handleEnumValue(result.data![0].aspectratio);
}

void handleEnumValue(EnumValue<AspectRatio> aspectValue) {
  if (aspectValue.value != null) {
    switch(aspectValue.value!) {
      case AspectRatio.ACADEMY:
        print('This movie is in Academy aspect');
        break;
      case AspectRatio.WIDESCREEN:
        print('This movie is in Widescreen aspect');
        break;
      case AspectRatio.ANAMORPHIC:
        print('This movie is in Anamorphic aspect');
        break;
      case AspectRatio.IMAX:
        print('This movie is in IMAX aspect');
    }
  } else {
    print('Unknown aspect ratio detected: ${aspectValue.stringValue}');
  }
}
```

## Enable client-side caching

SQL Connect has an optional client-side caching feature, which you
can enable by editing the `connector.yaml` file. When this feature is enabled,
the generated client SDKs will locally cache query responses, which can reduce
the number of database requests your app makes and enables the
database-dependent portions of your app to work when network availability is
interrupted.

To enable client-side caching, add a client caching configuration to your
connector configuration:


```yaml
generate:
  javascriptSdk:
    outputDir: ../dart/
    package: "dataconnect_generated"
    clientCache:
maxAge: 5s
storage: memory
```

<br />

This configuration has two parameters, both optional:

- `maxAge`: The maximum age a cached response can be before the client SDK
  fetches fresh values. Examples: "0", "30s", "1h30m".

  The default value for `maxAge` is `0`, which means that responses are cached,
  but the client SDK will always fetch fresh values. The cached values will only
  be used when `CACHE_ONLY` is specified to `execute()` and the initial result returned from `subscribe()`.
- `storage`: The client SDK can be configured to cache responses either in
  `persistent` storage or in `memory`. Results cached in `persistent` storage
  will persist across app restarts. When targeting Android or iOS, the default is `persistent`. When targeting web browsers, only `memory` storage is supported.

After you update your connector's caching configuration, regenerate your client
SDKs and rebuild your app. Once you have done so, `execute()`
and `subscribe()` will cache
responses and use cached values according to the policy you configured. This
generally happens automatically, without any additional steps on your part;
however, note the following:

- The default behavior of `execute()` is as described above: if a
  result is cached for a query and the cached value is not older than `maxAge`,
  then use the cached value. This default behavior is called the `PREFER_CACHE`
  policy.

  You can also specify to individual invocations of `execute()` to
  either only serve cached values (`CACHE_ONLY`) or to unconditionally fetch
  fresh values from the server (`SERVER_ONLY`).


  ```dart
  await queryRef.execute(fetchPolicy: QueryFetchPolicy.cacheOnly);
  ```

  ```dart
  await queryRef.execute(fetchPolicy: QueryFetchPolicy.serverOnly);
  ```
- When you call `subscribe()`, it will always immediately return the
  cached content if it exists, regardless of the `maxAge` setting. Subsequent
  calls to `execute()` will notify listeners according to the
  configured `maxAge`.

## Use mutations on the client side

Mutations are accessible in the same way as queries.

```dart
await MoviesConnector.instance.createMovie({ title: 'Empire Strikes Back', releaseYear: 1980, genre: "Sci-Fi" }).rating(5).execute();
```

## Prototype and test your Flutter apps

### Instrument clients to use a local emulator

You can use the SQL Connect emulator, whether from the
SQL Connect VS Code extension or from the CLI.

Instrumenting the app to connect to the emulator is the same for both scenarios.

```dart
import 'package:firebase_data_connect/firebase_data_connect.dart';
import 'generated/movies.dart';

MoviesConnector.instance.dataConnect
          .useDataConnectEmulator('127.0.0.1', 9399);

// Make calls from your app
QueryRef<ListMoviesData, void> ref = MoviesConnector.instance.listMovies.ref();
```

To switch to production resources, comment out lines for connecting to the
emulator.

## Data types in the Dart SDK

The SQL Connect server represents common GraphQL data types. These
are represented in the SDK as follows.

| SQL Connect Type | Dart |
|---|---|
| Timestamp | firebase_data_connect.Timestamp |
| Int (32-bit) | int |
| Date | DateTime |
| UUID | string |
| Int64 | int |
| Float | double |
| Boolean | bool |
| Any | firebase_data_connect.AnyValue |