### Install Flutter Dependencies Source: https://docs.amplify.aws/flutter/start/quickstart After adding dependencies to `pubspec.yaml`, run this command to install them. ```bash flutter pub get ``` -------------------------------- ### Initialize Amplify Project Source: https://docs.amplify.aws/flutter/start/quickstart Run this command to scaffold Amplify backend files into your existing Flutter project. ```bash npm create amplify@latest -y ``` -------------------------------- ### Navigate to Project Directory Source: https://docs.amplify.aws/flutter/start/quickstart Change your current directory to the newly created Flutter project. ```bash cd my_amplify_app ``` -------------------------------- ### Deploy Backend with Sandbox Source: https://docs.amplify.aws/flutter/start/quickstart Use this command to deploy your backend using Amplify's per-developer cloud sandbox. Specify `--outputs-format dart` and `--outputs-out-dir lib` for Flutter integration. ```bash npx ampx sandbox --outputs-format dart --outputs-out-dir lib ``` -------------------------------- ### Create New Flutter Project Source: https://docs.amplify.aws/flutter/start/quickstart Use this command to create a new Flutter project for your application. ```bash flutter create my_amplify_app ``` -------------------------------- ### Amplify Project Structure Source: https://docs.amplify.aws/flutter/start/quickstart This shows the typical file structure created by `create-amplify` within your project. ```tree ├── amplify/ │ ├── auth/ │ │ └── resource.ts │ ├── data/ │ │ └── resource.ts │ ├── backend.ts │ └── package.json ├── node_modules/ ├── .gitignore ├── package-lock.json ├── package.json └── tsconfig.json ``` -------------------------------- ### Initialize and Refresh Todo List Source: https://docs.amplify.aws/flutter/start/quickstart Initializes a list to hold 'Todo' items and calls '_refreshTodos' in 'initState'. This ensures the list is populated when the widget is first created. ```dart List _todos = []; @override void initState() { super.initState(); _refreshTodos(); } ``` -------------------------------- ### Implement Todo Creation in UI Source: https://docs.amplify.aws/flutter/start/quickstart Creates a 'TodoScreen' widget with a floating action button that generates and saves a new 'Todo' item using 'ModelMutations.create'. Handles success and error responses. ```dart class TodoScreen extends StatefulWidget { const TodoScreen({super.key}); @override State createState() => _TodoScreenState(); } class _TodoScreenState extends State { @override Widget build(BuildContext context) { return Scaffold( floatingActionButton: FloatingActionButton.extended( label: const Text('Add Random Todo'), onPressed: () async { final newTodo = Todo( id: uuid(), content: "Random Todo ${DateTime.now().toIso8601String()}", isDone: false, ); final request = ModelMutations.create(newTodo); final response = await Amplify.API.mutate(request: request).response; if (response.hasErrors) { safePrint('Creating Todo failed.'); } else { safePrint('Creating Todo successful.'); } }, ), body: const Placeholder(), ); } } ``` -------------------------------- ### Create Todo Item with Amplify Source: https://docs.amplify.aws/flutter/start/quickstart This code snippet demonstrates how to create a new Todo item and send it to the Amplify API. It includes error handling for the mutation. ```dart final newTodo = Todo( id: uuid(), content: "Random Todo ${DateTime.now().toIso8601String()}", isDone: false, ); final request = ModelMutations.create(newTodo); final response = await Amplify.API.mutate(request: request).response; if (response.hasErrors) { safePrint('Creating Todo failed.'); } else { safePrint('Creating Todo successful.'); } _refreshTodos(); ``` -------------------------------- ### Configure Amplify and Use Authenticator Source: https://docs.amplify.aws/flutter/start/quickstart Update your `main.dart` to configure Amplify with Cognito and wrap your app with the `Authenticator` widget for a pre-built login experience. ```dart import 'package:amplify_auth_cognito/amplify_auth_cognito.dart'; import 'package:amplify_authenticator/amplify_authenticator.dart'; import 'package:amplify_flutter/amplify_flutter.dart'; import 'package:flutter/material.dart'; import 'amplify_outputs.dart'; Future main() async { try { WidgetsFlutterBinding.ensureInitialized(); await _configureAmplify(); runApp(const MyApp()); } on AmplifyException catch (e) { runApp(Text("Error configuring Amplify: ${e.message}")); } } Future _configureAmplify() async { try { await Amplify.addPlugin(AmplifyAuthCognito()); await Amplify.configure(amplifyConfig); safePrint('Successfully configured'); } on Exception catch (e) { safePrint('Error configuring Amplify: $e'); } } class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return Authenticator( child: MaterialApp( builder: Authenticator.builder(), home: const Scaffold( body: Center( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ SignOutButton(), Text('TODO Application'), ], ), ), ), ), ); } } ``` -------------------------------- ### Configure Amplify with API Plugin Source: https://docs.amplify.aws/flutter/start/quickstart Updates the Amplify configuration in 'main.dart' to include the AmplifyAuthCognito and AmplifyAPI plugins, specifying the generated ModelProvider for API interactions. ```dart Future _configureAmplify() async { try { await Amplify.addPlugins( [ AmplifyAuthCognito(), AmplifyAPI( options: APIPluginOptions( modelProvider: ModelProvider.instance, ), ), ], ); await Amplify.configure(amplifyConfig); safePrint('Successfully configured'); } on Exception catch (e) { safePrint('Error configuring Amplify: $e'); } } ``` -------------------------------- ### Fetch Todos from API Source: https://docs.amplify.aws/flutter/start/quickstart Implements the '_refreshTodos' function to query all 'Todo' items from the API using 'ModelQueries.list'. Updates the UI state with the fetched todos and logs any errors. ```dart Future _refreshTodos() async { try { final request = ModelQueries.list(Todo.classType); final response = await Amplify.API.query(request: request).response; final todos = response.data?.items; if (response.hasErrors) { safePrint('errors: ${response.errors}'); return; } setState(() { _todos = todos!.whereType().toList(); }); } on ApiException catch (e) { safePrint('Query failed: $e'); } } ``` -------------------------------- ### Generate GraphQL Client Code Source: https://docs.amplify.aws/flutter/start/quickstart Generates Dart model classes from the Amplify Data schema to facilitate interaction with the backend API. Ensure the output directory is set to 'lib/models'. ```bash npx ampx generate graphql-client-code --format modelgen --model-target dart --out lib/models ``` -------------------------------- ### Define Todo Data Model with Authorization Source: https://docs.amplify.aws/flutter/start/quickstart Defines a 'Todo' model with 'content' and 'isDone' fields and sets up owner-based authorization. Configures the default authorization mode to use user pool tokens. ```typescript import { type ClientSchema, a, defineData } from "@aws-amplify/backend"; const schema = a.schema({ Todo: a .model({ content: a.string(), isDone: a.boolean(), }) .authorization(allow => [allow.owner()]) }); export type Schema = ClientSchema; export const data = defineData({ schema, authorizationModes: { defaultAuthorizationMode: "userPool", }, }); ``` -------------------------------- ### Add Amplify Dependencies to Flutter Source: https://docs.amplify.aws/flutter/start/quickstart Include these dependencies in your `pubspec.yaml` file to integrate Amplify with your Flutter application. ```yaml dependencies: amplify_flutter: ^2.0.0 amplify_auth_cognito: ^2.0.0 amplify_authenticator: ^2.0.0 ``` -------------------------------- ### Integrate TodoScreen into App Structure Source: https://docs.amplify.aws/flutter/start/quickstart Updates the 'MyApp' widget to include the 'TodoScreen' within a 'SafeArea' and 'Scaffold', ensuring it's displayed alongside a 'SignOutButton' after authentication. ```dart class MyApp extends StatelessWidget { const MyApp({super.key}); @override Widget build(BuildContext context) { return Authenticator( child: MaterialApp( builder: Authenticator.builder(), home: const SafeArea( child: Scaffold( body: Column( children: [ SignOutButton(), Expanded(child: TodoScreen()), ], ), ), ), ), ); } } ``` -------------------------------- ### Add Amplify API Dependency Source: https://docs.amplify.aws/flutter/start/quickstart Adds the 'amplify_api' package to your Flutter project's dependencies in 'pubspec.yaml' to enable communication with the Amplify API. ```yaml dependencies: amplify_api: ^2.0.0 ``` -------------------------------- ### Update Todo Item with Amplify Source: https://docs.amplify.aws/flutter/start/quickstart Integrate this code into the `onChanged` method of a `CheckboxListTile.adaptive` to update a Todo item's `isDone` status via Amplify API. It handles success and error responses. ```dart final request = ModelMutations.update( todo.copyWith(isDone: isChecked!), ); final response = await Amplify.API.mutate(request: request).response; if (response.hasErrors) { safePrint('Updating Todo failed. ${response.errors}'); } else { safePrint('Updating Todo successful.'); await _refreshTodos(); } ``` -------------------------------- ### Delete Todo Item with Amplify Source: https://docs.amplify.aws/flutter/start/quickstart Add this code to the `confirmDismiss` method of a `Dismissible` widget to enable deleting a Todo item by swiping. It sends a delete mutation to the Amplify API and refreshes the list upon success. ```dart if (direction == DismissDirection.endToStart) { final request = ModelMutations.delete(todo); final response = await Amplify.API.mutate(request: request).response; if (response.hasErrors) { safePrint('Updating Todo failed. ${response.errors}'); } else { safePrint('Updating Todo successful.'); await _refreshTodos(); return true; } } return false; ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.