Join us at MongoDB.local London on 7 May to unlock new possibilities for your data. Use WEB50 to save 50%.
Register now >
Docs Menu
Docs Home
/ /
Atlas App Services

Connect to App Services - Flutter SDK

La App El cliente es la interfaz con el backend de Atlas App Services. Proporciona acceso a funciones de App Services como la autenticación de usuarios y la sincronización de dispositivos.

  1. Crear una aplicación de servicios de aplicaciones

  2. Find the App ID in the App Services UI

Changed in version 1.7.0: App must be created on the main isolate.

Create an App instance to access App Services features throughout your client application. We recommend that you create the App instance only once on the main isolate, ideally as soon as the app starts.

  1. Obtén el ID de tu App de Servicios de aplicaciones desde la Interfaz de usuario Realm. Para saber cómo, consulta Encuentra tu ID de la aplicación.

  2. Crear una AppConfiguration objeto con el ID de aplicación de su aplicación como argumento.

  3. Crea una Aplicación con el AppConfiguration que acabas de crear. En Flutter v1.7.0 y más adelante, esto debe hacerse en el aislado principal, de lo contrario el SDK arroja un error.

Después de App crear, puede acceder a la App instancia construida en un aislamiento en segundo plano App.getById mediante. Consulte la sección "Obtener aplicación por ID" en esta página para obtener más información.

final appConfig = AppConfiguration(appId);
final app = App(appConfig);

Puedes crear varias instancias de un cliente de aplicación para conectarte a múltiples aplicaciones. Todas las instancias de cliente de aplicación que comparten el mismo ID de la aplicación utilizan la misma conexión subyacente.

Importante

Changing an App Config After Initializing the App

Changed in version 1.8.0: baseUrl is not cached in the AppConfiguration

When you initialize the App client, the configuration is cached internally. Attempting to close and then re-open an App with a changed configuration within the same process has no effect. The client continues to use the cached configuration.

In Flutter SDK version 1.8.0 and later, the baseUrl is no longer cached in the App configuration. This means that you can change the baseUrl, and the App client will use the updated configuration. In earlier SDK versions, changes to the baseUrl in a cached App configuration have no effect.

Deprecated since version 1.6.0: App.localAppName and App.localAppVersion are no longer used.

You can add optional arguments to the AppConfiguration for more granular control of your App client. You may want to add things like custom timeouts for connections or keys for local metadata encryption. To learn about the available configuration options, refer to the AppConfiguration reference documentation.

final appConfig = AppConfiguration(appId,
defaultRequestTimeout: const Duration(seconds: 120)
// ... see reference docs for all available configuration options
);

Nota

Conectarse usando Android 7 o anterior

The default HTTP client included with the Realm Flutter SDK does not work for apps running on Android 7 or older. To work around this, you must add a custom HTTP client to your AppConfiguration. To learn more, refer to Connect to App Services Using Android 7 or Older.

Novedad en la versión 1.7.0.

After you have created an App instance on the main isolate, you can access the constructed instance on a background isolate by passing the App ID to the App.getById() method. Then, you can use it to work with the App and users as needed.

// Create an App instance once on main isolate,
// ideally as soon as the app starts
final appConfig = AppConfiguration(appId);
final app = App(appConfig);
final receivePort = ReceivePort();
// Later, access the App instance on background isolate
await Isolate.spawn((List<Object> args) async {
final sendPort = args[0] as SendPort;
final appId = args[1] as String;
try {
final backgroundApp = App.getById(appId);
// ... Access App users
final user = backgroundApp?.currentUser!;
// Use the App and user as needed.
sendPort.send('Background task completed');
} catch (e) {
sendPort.send('Error: $e');
}
}, [receivePort.sendPort, appId]);

By default, Atlas Device SDK connects to Atlas using the global baseUrl of https://services.cloud.mongodb.com. In some cases, you may want to connect to a different server:

  • Tu aplicación de App Services utiliza una implementación local y quieres conectarte directamente a un baseUrl local en tu región.

Para obtener más información, consulte la documentación de Servicios de aplicaciones de implementación local.

You can specify a baseUrl in the AppConfiguration:

// Specify a baseUrl to connect to a server other than the default
final appConfig =
AppConfiguration(appId, baseUrl: Uri.parse('https://example.com'));
var app = App(appConfig);

New in version 1.8.0.

Changed in version 2.2.0: updateBaseUrl accepts null value

En algunos casos, podrías querer cambiar el baseUrl mientras la aplicación está en funcionamiento.

To change the baseUrl during runtime, call the experimental app.updateBaseUrl method. You can pass null to reset the baseUrl to the default value.

// Specify a custom baseUrl to connect to.
// In this case, a custom server instance running on the device.
final appConfig = AppConfiguration(customServerAppId,
baseUrl: Uri.parse('http://localhost:80'));
var app = App(appConfig);
// ... log in a user and use the app ...
// Later, change the baseUrl to the default:
// https://services.cloud.mongodb.com
await app.updateBaseUrl(null);

Esta API es experimental y puede cambiar en futuras versiones.

Si se desea cambiar el baseUrl después de que un usuario haya iniciado sesión y se haya abierto una base de datos sincronizada, la app debe realizar un restablecimiento del cliente. Para obtener más información, consulta restablecimiento del cliente.

Perform the following in your code:

  1. Pausar la sesión de sincronización

  2. Actualice el baseUrl utilizando el método app.updateBaseUrl

  3. Re-authenticate the user to log in using the new baseUrl

  4. Open a synced database pulling data from the new server

Both the server and the client must be online for the user to authenticate and connect to the new server. If the server is not online or the client does not have a network connection, the user cannot authenticate and open the database.

Volver

Atlas App Services

En esta página