Auth Implementation

  • Steps

    1. AuthController

    
                  import 'package:get/get.dart';
    
    class AuthController extends GetxController {
      var isAuthenticated = false.obs; // Observable for authentication status
    
      void login() {
        // Perform login logic
        // If successful, set isAuthenticated to true
        isAuthenticated.value = true;
      }
    
      void logout() {
        // Perform logout logic
        // Set isAuthenticated to false
        isAuthenticated.value = false;
      }
    }
    
    
    
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return GetMaterialApp(
          title: 'Auth Example',
          home: HomePage(),
        );
      }
    }
    
    

    3. Authentication Flow in Widgets:

    
    import 'package:flutter/material.dart';
    import 'package:get/get.dart';
    
    class HomePage extends StatelessWidget {
      final AuthController _authController = Get.put(AuthController());
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Authentication Example'),
          ),
          body: Center(
            child: Obx(() {
              return _authController.isAuthenticated.value
                  ? AuthenticatedScreen() // User is authenticated
                  : UnauthenticatedScreen(); // User is not authenticated
            }),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              _authController.login(); // Simulate login action
            },
            child: Icon(Icons.login),
          ),
        );
      }
    }
    
    class AuthenticatedScreen extends StatelessWidget {
      final AuthController _authController = Get.find();
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Welcome!'),
            ElevatedButton(
              onPressed: () {
                _authController.logout(); // Perform logout action
              },
              child: Text('Logout'),
            ),
          ],
        );
      }
    }
    
    class UnauthenticatedScreen extends StatelessWidget {
      final AuthController _authController = Get.find();
    
      @override
      Widget build(BuildContext context) {
        return Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('Please log in to continue.'),
            ElevatedButton(
              onPressed: () {
                _authController.login(); // Perform login action
              },
              child: Text('Login'),
            ),
          ],
        );
      }
    }