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

# Email Password Authentication with flutter

> Learn how to build authentication with Zeromagic using Flutter

In this tutorial, we will be using **Email & Password** authentication system with Flutter Frontend. We will create a simple login application that will allow users to sign in to their account and redirect them to the dashboard screen.

## Step 1 : Create the Login and Dashboard Screens

1. Create a new Flutter project using the following command.

```bash theme={null}
flutter create zeromagic_auth
```

2. Add this dependency to your package's pubspec.yaml file:

```yaml theme={null}
dependencies:
    flutter:
        sdk: flutter
    http: ^1.1.0    
```

3. Add the following code in your `main.dart` file. This contains Login and Dashboard Screens

```dart main.dart theme={null}
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Zeromagic Auth App',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: LoginPage(),
    );
  }
}

class LoginPage extends StatefulWidget {
  @override
  _LoginPageState createState() => _LoginPageState(); 
}

class _LoginPageState extends State<LoginPage> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isLoading = false;

  Future<void> _login() async {
    setState(() {
      _isLoading = true;
    });

    final response = await http.post(
      Uri.parse('{auth_base_url}/{auth_endpoint_path}'),
      headers: {
        'Content-Type': 'application/json',
        'APP-KEY': '{your_app_key}',
        },
      body: jsonEncode({
        'email': _emailController.text,
        'password': _passwordController.text,
      }),
    );

    setState(() {
      _isLoading = false;
    });

    if (response.statusCode == 200) {
      final Map<String, dynamic> responseData = json.decode(response.body);
      if (responseData['MSG'] == 'SUCCESS') {
        Navigator.of(context).pushReplacement(
          MaterialPageRoute(
            builder: (context) => DashboardPage(
              email: responseData['BODY']['email'],
              userId: responseData['BODY']['user_id'],
            ),
          ),
        );
      } else {
        _showErrorDialog(responseData['ERR'] ?? 'Unknown error occurred');
      }
    } else {
      _showErrorDialog('Failed to login. Please try again.');
    }
  }

  void _showErrorDialog(String message) {
    showDialog(
      context: context,
      builder: (ctx) => AlertDialog(
        title: Text('An Error Occurred'),
        content: Text(message),
        actions: <Widget>[
          TextButton(
            child: Text('Okay'),
            onPressed: () {
              Navigator.of(ctx).pop();
            },
          )
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Login'),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextField(
                controller: _emailController,
                decoration: InputDecoration(labelText: 'Email'),
                keyboardType: TextInputType.emailAddress,
              ),
              TextField(
                controller: _passwordController,
                decoration: InputDecoration(labelText: 'Password'),
                obscureText: true,
              ),
              SizedBox(height: 20),
              _isLoading
                  ? CircularProgressIndicator()
                  : ElevatedButton(
                      onPressed: _login,
                      child: Text('Login'),
                    ),
            ],
          ),
        ),
      ),
    );
  }
}

class DashboardPage extends StatelessWidget {
  final String email;
  final String userId;

  DashboardPage({required this.email, required this.userId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Dashboard'),
      ),
      body: Center(
        child: Padding(
          padding: EdgeInsets.all(16.0),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              Text(
                'Welcome, $email',
                style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 10),
              Text(
                'User ID: $userId',
                style: TextStyle(fontSize: 16),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
```

## Step 2 : Setup Authentication in Zeromagic

1. Create and open a new `Project` in the console. Add a `Database` to the project. You can use the database spinned up by Zeromagic or connect your own database. Here we are using the cosmosdb database provided by Zeromagic. To add a database, click on the `Create Database` on the `Database` section button and add your database.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-database.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=a6e7391c60c7ef6988e7fcaa10d1ed1a" alt="Create Database" width="1849" height="885" data-path="assets/images/authentication-add-database.png" />

   > Refer here to know more about: [Creating Database on the platform](/datasources/quickstart)

2. Create a new environment and map the added database to the environment. Here we are using the `development` environment and `employees` database

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-environment.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=9fc04a7dd437fdc9b3dbfac20ba7dcfb" alt="Create environment" width="1844" height="890" data-path="assets/images/authentication-add-environment.png" />

   > Refer here to know more about: [Creating Environments on the platform](/basics/environment)

3. Add the `Email & Password` authentication connection under Methods. Click `Add Connection` to create a new connection.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-methods.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=da784038f276ab5a3beeeb8a31de6f51" alt="Add Authentication" width="1863" height="921" data-path="assets/images/authentication-add-methods.png" />

   > Refer here to know more about: [Adding Authentication on the platform](/authentication/quickstart)

4. Now, go to `Environments` sections and select the environment you created. Copy the `Auth Endpoint URL` from the environment details. This is your authentication endpoint URL where you will be sending the APi requests. Your Auth endpoint URL looks similar to this:

   ```curl Auth Endpoint theme={null}
   http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/
   ```

5. Before making the APi request, let's **create a new user credentials** in the database for this example. You can **skip this step if your preferring to go with registering the user** and login with that user credentials. We do provide endpoints to create a new user also.

   <img src="https://mintcdn.com/zeromagiclabsprivatelimited/h_DeJnPWvd8dA9lO/assets/images/authentication-add-new-user.png?fit=max&auto=format&n=h_DeJnPWvd8dA9lO&q=85&s=adf8a4c8a567fcbe8fa55336acad0959" alt="Create User" width="1863" height="929" data-path="assets/images/authentication-add-new-user.png" />

   > Refer here to know more about: [Creating User on the platform](/authentication/users)

## Step 3 : Making the API Request

1. Replace the `{auth_base_url}/{auth_endpoint_path}` in the `main.dart` file with the copied URL from the environment details and with the path to the email password login endpoint.
   Here the `{auth_base_url}` is `http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/` and `{auth_endpoint_path}` is `/email-password-login`.

   > Note: Replace the `auth_base_url` ith your actual URL. Refer to the [Authentication API Reference](/authentication/api/generalinfo) for more details on the API endpoints.

2. Replace the `{your_app_key}` with your actual `APP-KEY` in the headers of `main.dart` file. You can find the `APP-ID` and `APP-KEY` in the `Manage -> Settings` section of your console.

   ```dart main.dart theme={null}
   final response = await http.post(
       //REPLACE HERE : `{auth_base_url}/{auth_endpoint_path}` with your auth base URL and api endpoint
     Uri.parse('http://authn.zeromagic.cloud/auth/86165f63f34e4be89809c2948c424a99/development/email-password-login'),
     headers: {
       'Content-Type': 'application/json',
       //REPLACE HERE : `{your_app_key}` with your APP-KEY
       'APP-KEY': 'lwc66BSZmPilT7UnNhlut2QFfRYr82ErXMqCYsKhtFM',
       },
     body: jsonEncode({
       'email': _emailController.text,
       'password': _passwordController.text,
     }),
   );
   ```

## Step 4 : Run the Application and Login

1. Run the flutter application. Enter the email and password of the user you created in the database and click on the `Login` button. Here login credentials users are
   ```curl Sample Credentails theme={null}
   email=genie@zeromagic.cloud
   password=genie#magic
   ```
2. If the login is successful, you will be redirected to the dashboard screen. If the login fails, you will see an alert message.

## Summary

In this tutorial, you learned how to create a simple login application using Flutter and authenticate users using the Zeromagic authentication API. This is a basic example to get you started with authentication in Zeromagic.

We provide more basic authentication methods and advanced method like social login. Feel free to explore the Authentication API Reference and reach out to us if you have any questions.

## Resource Links

* [Authentication API Reference](/authentication/api/generalinfo)
* [Flutter Documentation](https://flutter.dev/docs)
