团队作业博客(五)flutter 结合 springBoot 完成登录 注册 功能

后端接口

 前端调用接口代码

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

import '../page/login.dart';


//注册功能
Future<void> register(
    BuildContext context,
    String username,
    String password,
    String username2,
    String phoneNumber,
    String email)
async {
  try {
    Dio dio = Dio();
    String checkUrl = "http://192.168.95.241:9090/user/checkUserNameExistence?userName=$username";
    Response checkResponse = await dio.get(checkUrl);

    if (checkResponse.data) {
      // 用户名已存在,提示用户无法注册
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('注册失败'),
            content: Text('用户名已存在,请选择其他用户名'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(); // 关闭对话框
                },
                child: Text('确定'),
              ),
            ],
          );
        },
      );
      return;
    }

    // 用户名不存在,可以进行注册
    String registerUrl = "http://192.168.95.241:9090/user";
    Map<String, dynamic> data = {
      "user_name": username,
      "user_password": password,
      "user_name2": username2,
      "user_phone": phoneNumber,
      "user_email": email
    };
    Response response = await dio.post(registerUrl, data: data);

    if (response.statusCode == 200) {
      // 注册成功
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('注册成功'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop(); // 关闭对话框
                  Navigator.of(context).pushReplacement( // 替换当前页面为登录页面
                    MaterialPageRoute(builder: (context) => LoginPage(key: UniqueKey())),
                  );
                },
                child: Text('确定'),
              ),
            ],
          );
        },
      );
    } else {
      // 注册失败
      showDialog(
        context: context,
        builder: (BuildContext context) {
          return AlertDialog(
            title: Text('注册失败'),
            content: Text('错误码: ${response.statusCode}'),
            actions: <Widget>[
              TextButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text('确定'),
              ),
            ],
          );
        },
      );
    }
  } catch (e) {
    // 请求过程中出现错误
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text('请求错误'),
          content: Text('$e'),
          actions: <Widget>[
            TextButton(
              onPressed: () {
                Navigator.of(context).pop();
              },
              child: Text('确定'),
            ),
          ],
        );
      },
    );
  }
}


//登录功能

Future<void> login(
    BuildContext context,
    String username,
    String password)
async {

    Dio dio = Dio();
    String checkUrl = "http://192.168.95.241:9090/user/checkCredentials";

    Map<String, dynamic> data = {
      "user_name": username,
      "user_password": password,

    };
    Response response = await dio.post(checkUrl, data: data);

    if (response.statusCode == 200) {
      bool isAuthenticated = response.data;

      if (isAuthenticated) {
        // 显示登录成功对话框
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('登录成功'),
              content: Text('欢迎回来!'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // 关闭对话框
                  },
                  child: Text('确定'),
                ),
              ],
            );
          },
        );
      } else {
        // 身份验证失败,显示错误消息或采取相应的操作
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('登录失败'),
              content: Text('用户名或密码不正确'),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop(); // 关闭对话框
                  },
                  child: Text('确定'),
                ),
              ],
            );
          },
        );
      }
    }
}





import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';

// 导入获取用户信息的方法
import '../Do/UserDao.dart';
import '../component/container.dart';
import '../component/drawer.dart';
import 'Home1.dart';
import 'login.dart';

class MyApp2 extends StatelessWidget {
  final String username;

  const MyApp2({Key? key, required this.username}) : super(key: key); // 调用父类构造函数

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: '心语航标',
      theme: ThemeData(
        primarySwatch: Colors.purple,
      ),
      home: MyHome2(username: username),
    );
  }
}

class MyHome2 extends StatefulWidget {
  final String username;

  const MyHome2({Key? key, required this.username}) : super(key: key);

  @override
  _MyHome2State createState() => _MyHome2State();
}

class _MyHome2State extends State<MyHome2> {
  Map<String, dynamic> userInfo = {}; // 初始化userInfo

  @override
  void initState() {
    super.initState();
    getUserInfo(widget.username); // 调用获取用户信息的方法
  }

  //登录查询用户信息
  Future<void> getUserInfo(String username) async {
    Dio dio = Dio();
    String apiUrl = "http://192.168.95.241:9090/user/findAll?user_name=$username";

    try {
      Response response = await dio.get(apiUrl);
      print(response);
      if (response.statusCode == 200) {
        setState(() {
          userInfo = response.data; // 更新userInfo
        });
      } else {
        setState(() {
          userInfo = {}; // 请求失败时将userInfo清空
        });
      }
    } catch (e) {
      print("Error fetching user info: $e");
      setState(() {
        userInfo = {}; // 发生异常时将userInfo清空
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: 4,
      child: Scaffold(
        appBar: AppBar(
          title: const Text('心语航标'),
          centerTitle: true,
          actions: <Widget>[
            IconButton(
              icon: const Icon(Icons.search),
              onPressed: () {
                // 搜索操作
              },
            ),
          ],
        ),
        drawer: buildCustomDrawer(
          accountEmail: userInfo['user_email'] ?? '未知邮箱',
          accountName: userInfo['user_name2'] ?? '未登录',
          currentAccountPictureAsset: 'assets/阿尼亚.jpg',
          drawerBackgroundAsset: 'assets/可可爱爱阿尼亚.jpg',
          drawerItems: [
            DrawerItem(title: '用户反馈', icon: Icons.feedback),
            DrawerItem(title: '系统设置', icon: Icons.settings),
            DrawerItem(title: '我要发布', icon: Icons.send),
            DrawerItem(title: '注销', icon: Icons.exit_to_app),
          ],
          onLoginPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => LoginPage(key: UniqueKey()),
              ),
            );
          },
        ),
        bottomNavigationBar: buildCustomBottomNavigationBar(
          tabs: [
            const Tab(icon: Icon(Icons.home), text: '首页'),
            const Tab(icon: Icon(Icons.article), text: '专栏'),
            const Tab(icon: Icon(Icons.chat_bubble), text: 'AI咨询'),
            const Tab(icon: Icon(Icons.notifications), text: '消息'),
          ],
          backgroundColor: Colors.black,
          height: 60.0,
          labelStyle: const TextStyle(height: 0, fontSize: 12),
        ),
        body: TabBarView(
          children: <Widget>[
            home1(mt: 'in_teher', key: GlobalKey()),
            const Text('data2'),
            const Text('data3'),
            const Text('data4'),
          ],
        ),
      ),
    );
  }
}

  

posted @ 2024-04-22 23:07  财神给你送元宝  阅读(80)  评论(0编辑  收藏  举报