• Flutter框架实现登录注册功能,不连接数据库


    要在Flutter框架中实现登录和注册功能,而不连接数据库,可以使用本地存储来存储用户信息。以下是一个简单的示例,演示如何使用本地存储来实现登录和注册功能。

    首先,我们需要添加 shared_preferences 插件到 pubspec.yaml 文件中:

    dependencies:
      flutter:
        sdk: flutter
      shared_preferences: ^0.5.13+4
    
    • 1
    • 2
    • 3
    • 4

    然后,在 lib 文件夹中创建一个新的文件夹 models,并在其中创建一个名为 user.dart 的文件。在 user.dart 文件中,定义一个简单的 User 类,用于表示用户信息:

    class User {
      final String username;
      final String password;
    
      User({required this.username, required this.password});
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    接下来,我们将在 lib 文件夹中创建一个名为 utils.dart 的文件,在其中定义一些工具函数。首先,我们将创建一个函数来保存用户信息到本地存储

    import 'package:shared_preferences/shared_preferences.dart';
    import 'package:your_app_name/models/user.dart';
    
    class Utils {
      static Future<void> saveUser(User user) async {
        final prefs = await SharedPreferences.getInstance();
        await prefs.setString('username', user.username);
        await prefs.setString('password', user.password);
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    然后,我们将创建一个函数来从本地存储中获取保存的用户信息:

    class Utils {
      // ...
    
      static Future<User?> getUser() async {
        final prefs = await SharedPreferences.getInstance();
        final username = prefs.getString('username');
        final password = prefs.getString('password');
    
        if (username != null && password != null) {
          return User(username: username, password: password);
        }
        
        return null;
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    现在,我们将在 lib 文件夹中创建一个名为 login.dart 的文件,在其中实现登录功能。首先,我们将创建一个简单的登录表单:

    import 'package:flutter/material.dart';
    import 'package:your_app_name/models/user.dart';
    import 'package:your_app_name/utils.dart';
    
    class LoginScreen extends StatefulWidget {
      
      _LoginScreenState createState() => _LoginScreenState();
    }
    
    class _LoginScreenState extends State<LoginScreen> {
      final _formKey = GlobalKey<FormState>();
      String _username = '';
      String _password = '';
    
      
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Login'),
          ),
          body: Padding(
            padding: EdgeInsets.all(16.0),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Username'),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter your username';
                      }
                      return null;
                    },
                    onSaved: (value) => _username = value!,
                  ),
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter your password';
                      }
                      return null;
                    },
                    onSaved: (value) => _password = value!,
                  ),
                  SizedBox(height: 16.0),
                  ElevatedButton(
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        _formKey.currentState!.save();
                        _login();
                      }
                    },
                    child: Text('Login'),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      void _login() async {
        final user = await Utils.getUser();
    
        if (user != null && user.username == _username && user.password == _password) {
          // 登录成功
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('Success'),
                content: Text('Logged in successfully'),
                actions: [
                  TextButton(
                    child: Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        } else {
          // 登录失败
          showDialog(
            context: context,
            builder: (BuildContext context) {
              return AlertDialog(
                title: Text('Error'),
                content: Text('Invalid credentials'),
                actions: [
                  TextButton(
                    child: Text('OK'),
                    onPressed: () {
                      Navigator.of(context).pop();
                    },
                  ),
                ],
              );
            },
          );
        }
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108

    然后,我们将在 lib 文件夹中创建一个名为 register.dart 的文件,在其中实现注册功能。类似地,我们将创建一个简单的注册表单:

    import 'package:flutter/material.dart';
    import 'package:your_app_name/models/user.dart';
    import 'package:your_app_name/utils.dart';
    
    class RegisterScreen extends StatefulWidget {
      
      _RegisterScreenState createState() => _RegisterScreenState();
    }
    
    class _RegisterScreenState extends State<RegisterScreen> {
      final _formKey = GlobalKey<FormState>();
      String _username = '';
      String _password = '';
    
      
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Register'),
          ),
          body: Padding(
            padding: EdgeInsets.all(16.0),
            child: Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Username'),
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter your username';
                      }
                      return null;
                    },
                    onSaved: (value) => _username = value!,
                  ),
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    validator: (value) {
                      if (value == null || value.isEmpty) {
                        return 'Please enter your password';
                      }
                      return null;
                    },
                    onSaved: (value) => _password = value!,
                  ),
                  SizedBox(height: 16.0),
                  ElevatedButton(
                    onPressed: () {
                      if (_formKey.currentState!.validate()) {
                        _formKey.currentState!.save();
                        _register();
                      }
                    },
                    child: Text('Register'),
                  ),
                ],
              ),
            ),
          ),
        );
      }
    
      void _register() async {
        final newUser = User(username: _username, password: _password);
        await Utils.saveUser(newUser);
    
        showDialog(
          context: context,
          builder: (BuildContext context) {
            return AlertDialog(
              title: Text('Success'),
              content: Text('Registered successfully'),
              actions: [
                TextButton(
                  child: Text('OK'),
                  onPressed: () {
                    Navigator.of(context).pop();
                    Navigator.of(context).pop(); // 返回登录页面
                  },
                ),
              ],
            );
          },
        );
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88

    最后,在 lib 文件夹中的 main.dart 文件中,我们将创建一个简单的登陆注册示例应用,包含一个首页和两个路由:/login/register。用户可以从首页导航到登录和注册页面:

    import 'package:flutter/material.dart';
    import 'package:your_app_name/login.dart';
    import 'package:your_app_name/register.dart';
    
    void main() {
      runApp(MyApp());
    }
    
    class MyApp extends StatelessWidget {
      
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Login & Register Demo',
          theme: ThemeData(
            primarySwatch: Colors.blue,
          ),
          initialRoute: '/',
          routes: {
            '/': (context) => HomeScreen(),
            '/login': (context) => LoginScreen(),
            '/register': (context) => RegisterScreen(),
          },
        );
      }
    }
    
    class HomeScreen extends StatelessWidget {
      
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: Text('Home'),
          ),
          body: Center(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, '/login');
                  },
                  child: Text('Login'),
                ),
                ElevatedButton(
                  onPressed: () {
                    Navigator.pushNamed(context, '/register');
                  },
                  child: Text('Register'),
                ),
              ],
            ),
          ),
        );
      }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55

    通过在 main.dart 中定义的初始路由和 routes,我们可以在各个页面之间进行导航。用户可以从首页进入登录页面完成登录,或者从首页进入注册页面完成注册。

    这只是一个简单的示例,演示如何在Flutter框架中实现登录和注册功能,而不连接数据库。实际应用中,您可能需要更完整和复杂的解决方案来处理更多的用户信息和功能。

  • 相关阅读:
    详解HTTP协议版本(HTTP/1.0、1.1、2.0、3.0区别)
    前端知识案例106-javascript基础语法-setTimeOut
    H5 的浏览器存储
    面试常考数据结构:红黑树、B树、B+树各自适用的场景
    java面试题-基础篇(万字总结,带答案,面试官问烂,跳槽必备)
    链表-0405合并有序链表
    vue非常实用的几行代码【日期处理、字符串处理、数组处理、颜色操作】
    缓存设计的创新之旅:架构的灵魂之一
    3.2 网络协议
    apifox导出ts类型
  • 原文地址:https://blog.csdn.net/zi2242975806/article/details/134068778