name27 / flutter

0 stars 0 forks source link

Getx AuthController #105

Open name27 opened 1 year ago

name27 commented 1 year ago

image image image image

main.dart

import 'package:auth_cotroller_app/controller/auth_controller.dart';
import 'package:auth_cotroller_app/controller/login_controller.dart';
import 'package:auth_cotroller_app/controller/main_controller.dart';
import 'package:auth_cotroller_app/view/login_page.dart';
import 'package:auth_cotroller_app/view/main_page.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      initialBinding: BindingsBuilder(() {
        Get.put(AuthController());
        Get.lazyPut(() => LoginController());
        Get.lazyPut(() => MainController());
      }),
      getPages: [
        GetPage(name: LoginPage.route, page: () => const LoginPage()),
        GetPage(name: MainPage.route, page: () => const MainPage())
      ],
      home: Scaffold(
        body: Center(
            child: TextButton(
                onPressed: () => Get.toNamed(LoginPage.route),
                child: const Text('Hello World'))),
      ),
    );
  }
}

main_page.dart

import 'package:auth_cotroller_app/controller/auth_controller.dart';
import 'package:auth_cotroller_app/controller/main_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MainPage extends GetView<MainController> {
  const MainPage({super.key});
  static String route = '/main';

  @override
  Widget build(BuildContext context) {
    var user = Get.find<AuthController>().user!;
    return Scaffold(
        bottomNavigationBar: Obx(
          () => BottomNavigationBar(
              onTap: controller.onPageTapped,
              currentIndex: controller.curPage.value,
              items: const [
                BottomNavigationBarItem(icon: Icon(Icons.home), label: 'Home'),
                BottomNavigationBarItem(
                    icon: Icon(Icons.person), label: 'Home'),
              ]),
        ),
        body: SafeArea(
          child: PageView(
            controller: controller.pageController,
            children: [
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '${user.username} 님 안녕하세요',
                    style: const TextStyle(fontSize: 22),
                  )
                ],
              ),
              Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  ListTile(
                    leading: const CircleAvatar(
                        //backgroundImage: NetworkImage(user),
                        ),
                    title: Text(user.username),
                    subtitle: Text(user.name),
                  ),
                  ListTile(
                    title: const Text('로그아웃하기'),
                    leading: const Icon(Icons.logout),
                    onTap: controller.logout,
                  )
                ],
              )
            ],
          ),
        ));
  }
}

api_routes.dart

class ApiRoutes{
  static const String authWithPassword = '/api/collections/users/auth-with-password';
}

user.dart

import 'dart:convert';

class User {
  String id;
  String username;
  String email;
  String name;
  User({
    required this.id,
    required this.username,
    required this.email,
    required this.name,
  });

  Map<String, dynamic> toMap() {
    return <String, dynamic>{
      'id': id,
      'username': username,
      'email': email,
      'name': name,
    };
  }

  factory User.fromMap(Map<String, dynamic> map) {
    return User(
      id: map['id'] as String,
      username: map['username'] as String,
      email: map['email'] as String,
      name: map['name'] as String,
    );
  }

  String toJson() => json.encode(toMap());

  factory User.fromJson(String source) =>
      User.fromMap(json.decode(source) as Map<String, dynamic>);
}

auth_controller.dart

import 'package:auth_cotroller_app/model/user.dart';
import 'package:auth_cotroller_app/util/api_routes.dart';
import 'package:auth_cotroller_app/view/login_page.dart';
import 'package:auth_cotroller_app/view/main_page.dart';
import 'package:dio/dio.dart';
import 'package:get/get.dart';

class AuthController extends GetxController {
  final Rxn<User> _user = Rxn();
  Dio dio = Dio();

  User? get user => _user.value;

  login(String id, String pw) async {
    dio.options.baseUrl = 'http://52.79.115.43:8090';
    try {
      var res = await dio.post(ApiRoutes.authWithPassword, data: {
        'identity': id,
        'password': pw,
      });
      if (res.statusCode == 200) {
        var user = User.fromMap(res.data['record']);
        _user(user);
      }
    } on DioError catch (e) {
      print(e.message);
      print(e.requestOptions.path);
    }
  }

  logout() {
    _user.value = null;
  }

  _handleAuthChanged(User? data) {
    if (data != null) {
      Get.toNamed(MainPage.route);
      return;
    }
    Get.toNamed(LoginPage.route);
    return;
  }

  @override
  void onInit() {
    super.onInit();
    ever(_user, (_handleAuthChanged));
  }
}

login_controller.dart

import 'package:auth_cotroller_app/controller/auth_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class LoginController extends GetxController {
  var idController = TextEditingController();
  var pwController = TextEditingController();

  login() {
    Get.find<AuthController>().login(idController.text, pwController.text);
  }
}

main_controller.dart

import 'package:auth_cotroller_app/controller/auth_controller.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';

class MainController extends GetxController {
  var pageController = PageController();
  RxInt curPage = 0.obs;
  onPageTapped(int v) {
    pageController.jumpToPage(v);
    curPage(v);
  }

  logout() {
    Get.find<AuthController>().logout();
  }
}