> ## Documentation Index
> Fetch the complete documentation index at: https://docs.magic.link/llms.txt
> Use this file to discover all available pages before exploring further.

# Flutter SDK Reference

> The Magic SDK for Flutter is your entry-point to secure, passwordless authentication for your mobile app. This guide will cover some important topics for getting started with Flutter APIs and to make the most of Magic's features.

## Overview

## Getting Started

The Magic class is the entry-point to the Magic SDK. It must be instantiated with a Magic **publishable** key.

### Installation

Add `magic_sdk` to your `pubspec.yaml`:

```yaml YAML icon="file" theme={null}
dependencies:
  flutter:
    sdk: flutter
  magic_sdk: ^6.0.1
```

Run the following command to install dependencies:

```bash Bash icon="square-terminal"  theme={null}
dart pub get
```

### Performance improvement (optional)

We use service workers for for better performance on web3 operations. They are enabled by default on Android, but if you'd like to take advantage of this performance boost on iOS as well, you'd have to enable app bound domains. To do that, add the following to your `Info.plist` and rebuild your app:

```xml plist icon="file-xml" theme={null}
<key>WKAppBoundDomains</key>
<array>
  <string>https://auth.magic.link</string>
</array>
```

### Constructor

`Magic()`

`Magic(apiKey, {MagicLocale locale})`

|           |             |                                                                                                                                                                   |
| --------- | ----------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Parameter | Type        | Definition                                                                                                                                                        |
| `apiKey`  | String      | Your **publishable** API Key retrieved from the Magic Dashboard.                                                                                                  |
| `locale?` | MagicLocale | Customize the language of Magic's modal, email and confirmation screen. See [Localization](/embedded-wallets/authentication/customization/localization) for more. |

`Magic.eth(String apiKey, { required EthNetwork network, MagicLocale locale})`

|           |            |                                                                                 |
| --------- | ---------- | ------------------------------------------------------------------------------- |
| Parameter | Type       | Definition                                                                      |
| `network` | EthNetwork | A representation of the connected Ethereum network (one of: mainnet or goerli). |

`Magic.custom(String apiKey, { required String rpcUrl, int? chainId, MagicLocale locale})`

|            |        |                                                                                                                                                              |
| ---------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| Parameter  | Type   | Definition                                                                                                                                                   |
| `rpcUrl`   | String | A URL pointing to your custom Ethereum Node.                                                                                                                 |
| `chainId?` | int    | Some Node infrastructures require you to pass an explicit chain ID. If you are aware that your Node requires this configuration, pass it here as an integer. |

### Initialization

```dart Dart icon="flutter" theme={null}
import "package:magic_sdk/magic_sdk.dart";

// Construct with an API key:
Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Construct with an API key and locale:
Magic.instance = Magic("PUBLISHABLE_API_KEY", locale: MagicLocale.en_US);

// Construct with an API key and network:
Magic.instance = Magic.eth("PUBLISHABLE_API_KEY", network: EthNetwork.goerli);

// Construct with an API key and custom node options:
Magic.instance = Magic.custom("PUBLISHABLE_API_KEY", rpcUrl: "https://your.custom.url/", chainId: 1);
```

## Auth Module

The Auth Module and its members are accessible on the Magic SDK instance by the `auth` property.

### `loginWithSMS`

Authenticate a user passwordlessly using a one-time code sent to the specified phone number.

[List of Currently Blocked Country Codes](/home/faq#questions-around-sms)

**Public Methods**

`Future<String> loginWithSMS({ required String email })`

|               |        |                                  |
| ------------- | ------ | -------------------------------- |
| Parameter     | Type   | Definition                       |
| `phoneNumber` | String | The phone number to log in with. |

**Returns**

* `Future<string>` The future resolves upon authentication request success and throws with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

**Example**

```dart Dart icon="flutter" theme={null}
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// log in a user by using text input Controller
try {
  var magic = Magic.instance;
  await magic.auth.loginWithSMS(phoneNumber: textController.text);
} catch {
  // Handle errors if required!
}
```

### `loginWithEmailOTP`

Authenticate a user passwordlessly using an email one-time code sent to the specified user's email address.

**Public Methods**

`Future<String> loginWithEmailOTP({ required String email })`

|           |        |                                |
| --------- | ------ | ------------------------------ |
| Parameter | Type   | Definition                     |
| `email`   | String | The user email to log in with. |

**Returns**

* `Future<string>` The future resolves upon authentication request success and throws with a specific error code if the request fails. The resolved value is a Decentralized ID token with a default 15-minute lifespan.

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// log in a user by using text input Controller
try {
  var magic = Magic.instance;
  await magic.auth.loginWithEmailOTP(email: textController.text);
} catch {
  // Handle errors if required!
}
```

## User Module

The User Module and it's members are accessible on the Magic SDK instance by the user property.

### `updateEmail`

Initiates the update email flow that allows a user to change their email address.

**Arguments**

`Future<bool> updateEmail({required String email, bool showUI = true})`

|           |         |                                                                                                                                                                                           |
| --------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Parameter | Type    | Definition                                                                                                                                                                                |
| `email`   | String  | The new email to update to.                                                                                                                                                               |
| `showUI?` | Boolean | If `true`, shows an out-of-the-box pending UI which includes instructions on which step of the confirmation process the user is on. Dismisses automatically when the process is complete. |

**Returns**

* `Future<boolean>`: The future resolves with a true boolean value if update email is successful and rejects with a specific error code if the request fails

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Initiates the flow to update a user's current email to a new one.
try {
  var magic = Magic.instance;

  /* Assuming user is logged in */
  await magic.user.updateEmail(email: 'new_user_email@example.com');
} catch {
  // Handle errors if required!
}

/**
 * Initiates the flow to update a user's current email to a new one,
 * without showing an out-of-the box UI.
 */
try {
  var magic = Magic.instance;

  /* Assuming user is logged in */
  await magic.user.updateEmail({ email: 'new_user_email@example.com', showUI: false });
} catch {
  // Handle errors if required!
}
```

### `getIdToken`

Generates a [Decentralized Id Token](/embedded-wallets/authentication/features/decentralized-id) which acts as a proof of authentication to resource servers.

**Arguments**

`Future<String> getIdToken({int lifespan = 900})`

|             |      |                                                                          |
| ----------- | ---- | ------------------------------------------------------------------------ |
| Parameter   | Type | Definition                                                               |
| `lifespan?` | int  | Will set the lifespan of the generated token. Defaults to 900s (15 mins) |

**Returns**

* `Future<string>`: Base64-encoded string representation of a JSON tuple representing `[proof, claim]`

**Example**

```dart Dart icon="flutter" theme={null}
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
var m = Magic.instance;
const idToken = await m.user.getIdToken();
} catch {
// Handle errors if required!
}
```

### `generateIdToken`

Generates a [Decentralized Id Token](/embedded-wallets/authentication/features/decentralized-id) with optional serialized data.

**Arguments**

`Future<String> generateIdToken({int lifespan = 900, String attachment = 'none'})`

|               |        |                                                                                      |
| ------------- | ------ | ------------------------------------------------------------------------------------ |
| Parameter     | Type   | Definition                                                                           |
| `lifespan?`   | int    | Will set the lifespan of the generated token. Defaults to 900s (15 mins)             |
| `attachment?` | String | Will set a signature of serialized data in the generated token. Defaults to `"none"` |

**Returns**

* `Future<string>`: Base64-encoded string representation of a JSON tuple representing `[proof, claim]`

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
  var m = Magic.instance;

  const idToken = await m.user.generateIdToken({ attachment: 'SERVER_SECRET' });
} catch {
  // Handle errors if required!
}
```

### `getInfo`

Retrieves information for the authenticated user.

**Arguments**

* *None*

**Returns**

* `Future<UserInfo>`: an object containing the issuer, email and cryptographic public address of the authenticated user

|                   |                                                            |                                                                                                                                   |
| ----------------- | ---------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
| Value             | Type                                                       | Definition                                                                                                                        |
| `issuer`          | String                                                     | The Decentralized ID of the user. In server-side use-cases, we recommend this value to be used as the user ID in your own tables. |
| `email`           | String                                                     | Email address of the authenticated user.                                                                                          |
| `publicAddress`   | String                                                     | The authenticated user's public address (a.k.a.: public key). Currently, this value is associated with the Ethereum blockchain.   |
| `isMfaEnabled`    | Boolean                                                    | A boolean indicating if user has multi-factor authentication enabled.                                                             |
| `recoveryFactors` | \_ `List<RecoveryFactor>`<br /> \_ `value`<br /> \* `type` |                                                                                                                                   |

**Example**

```dart Dart icon="flutter" theme={null}
import "package:magic_sdk/magic_sdk.dart";

Magic.instance = Magic("PUBLISHABLE_API_KEY");

// Assumes a user is already logged in
try {
var m = Magic.instance
await m.user.getInfo();
} catch {
// Handle errors if required!
}
```

### `isLoggedIn`

Checks if a user is currently logged in to the Magic SDK.

**Arguments**

* *None*

**Returns**

* `Future<Boolean>`

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

try {
  const isLoggedIn = await m.user.isLoggedIn();
  debugPrint(isLoggedIn); // => `true` or `false`
} catch {
  // Handle errors if required!
}
```

### `logout`

Logs out the currently authenticated Magic user

**Arguments**

* *None*

**Returns**

* `Future<Boolean>`

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';

Magic.instance = Magic("PUBLISHABLE_API_KEY");

try {
  await m.user.logout();
  debugPrint(await m.user.isLoggedIn()); // => `false`
} catch {
  // Handle errors if required!
}
```

## OAuth Module

The OAuth Module and it's members are accessible on the Magic SDK instance by the `oauth` property.

### `loginWithPopup`

Starts the OAuth 2.0 login flow.

**Arguments**

* `provider` (String): The OAuth provider being used for login
* `redirectURI` (String): A URL a user is sent to after they successfully log in
* `scope?` (Array): Defines the specific permissions an application requests from a user

**Returns**

* *None*

**Valid Providers**

|           |               |
| --------- | ------------- |
| Name      | Argument      |
| Google    | `'google'`    |
| Facebook  | `'facebook'`  |
| Twitter   | `'twitter'`   |
| Apple     | `'apple'`     |
| Discord   | `'discord'`   |
| GitHub    | `'github'`    |
| LinkedIn  | `'linkedin'`  |
| Bitbucket | `'bitbucket'` |
| GitLab    | `'gitlab'`    |
| Twitch    | `'twitch'`    |
| Microsoft | `'microsoft'` |

**Example**

```dart Dart icon="flutter" theme={null}
import 'package:magic_sdk/magic_sdk.dart';
import 'package:magic_ext_oauth/magic_ext_oauth.dart';

Magic.instance = Magic("YOUR_PUBLISHABLE_KEY");
Magic magic = Magic.instance;

var configuration = OAuthConfiguration(provider: OAuthProvider.GITHUB, redirectURI: 'YOUR_APP_SCHEME://');
var result = await magic.oauth.loginWithPopup(configuration);
```

## Resources

* [GitHub](https://github.com/magiclabs/magic-flutter)
* ⁠[Demo](https://github.com/magiclabs/magic-flutter/tree/main/magic_demo)
* [Goerli Testnet Faucet](https://goerlifaucet.com)
