Flutter认证管理插件nhost_auth_dart的使用

发布于 1周前 作者 phonegap100 来自 Flutter

Flutter认证管理插件nhost_auth_dart的使用

nhost_auth_dart 是一个用于 Flutter 应用的认证管理插件。通过它可以轻松地实现用户注册、登录等功能。以下是使用该插件的详细步骤。

获取开始

首先,你需要从 Nhost 控制台获取你的子域名和区域信息。

import 'package:nhost_auth_dart/nhost_auth_dart.dart';

void main() async {
  // 设置客户端
  final auth = NhostAuthClient(url: 'YOUR_SUBDOMAIN.auth.nhost.run');

  try {
    // 用户通过邮箱和密码进行登录
    await auth.signInEmailPassword(
      email: 'user-1@nhost.io',
      password: 'password-1',
    );

    // 打印当前用户的部分信息
    final currentUser = auth.currentUser;
    if (currentUser != null) {
      print('currentUser.id: ${currentUser.id}');
      print('currentUser.displayName: ${currentUser.displayName}');
      print('currentUser.email: ${currentUser.email}');
      
      // 登出
      await auth.signOut();
    }
  } catch (e) {
    // 捕获并打印错误信息
    print(e);
  }

  // 释放资源
  auth.close();
}

最新发布

pubspec.yaml 文件中添加依赖项:

dependencies:
  nhost_auth_dart: ^2.0.0

完整示例

以下是一个完整的示例代码,展示了如何使用 nhost_auth_dart 插件完成用户注册、登录和登出操作。

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Nhost Auth Example')),
        body: Center(
          child: AuthExample(),
        ),
      ),
    );
  }
}

class AuthExample extends StatefulWidget {
  [@override](/user/override)
  _AuthExampleState createState() => _AuthExampleState();
}

class _AuthExampleState extends State<AuthExample> {
  final TextEditingController _emailController = TextEditingController();
  final TextEditingController _passwordController = TextEditingController();
  bool _isSignedIn = false;

  Future<void> _signIn() async {
    final auth = NhostAuthClient(url: 'YOUR_SUBDOMAIN.auth.nhost.run');
    try {
      await auth.signInEmailPassword(
        email: _emailController.text,
        password: _passwordController.text,
      );
      final currentUser = auth.currentUser;
      if (currentUser != null) {
        setState(() {
          _isSignedIn = true;
        });
      }
    } catch (e) {
      print(e);
    }
  }

  Future<void> _signOut() async {
    final auth = NhostAuthClient(url: 'YOUR_SUBDOMAIN.auth.nhost.run');
    try {
      await auth.signOut();
      setState(() {
        _isSignedIn = false;
      });
    } catch (e) {
      print(e);
    }
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          TextField(
            controller: _emailController,
            decoration: InputDecoration(labelText: 'Email'),
          ),
          TextField(
            controller: _passwordController,
            obscureText: true,
            decoration: InputDecoration(labelText: 'Password'),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _signIn,
            child: Text('Sign In'),
          ),
          SizedBox(height: 16),
          ElevatedButton(
            onPressed: _isSignedIn ? _signOut : null,
            child: Text('Sign Out'),
          ),
          SizedBox(height: 16),
          Text(_isSignedIn ? 'Signed In' : 'Not Signed In')
        ],
      ),
    );
  }
}

更多关于Flutter认证管理插件nhost_auth_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter认证管理插件nhost_auth_dart的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用Flutter认证管理插件nhost_auth_dart的示例代码。nhost_auth_dart是一个用于Flutter应用的认证插件,它允许你轻松集成Nhost认证服务。以下是一个基本的示例,展示了如何使用这个插件进行用户注册、登录和注销。

首先,确保你已经在你的pubspec.yaml文件中添加了nhost_auth_dart依赖:

dependencies:
  flutter:
    sdk: flutter
  nhost_auth_dart: ^最新版本号

然后,运行flutter pub get来安装依赖。

接下来,在你的Flutter项目中,你可以按照以下步骤使用nhost_auth_dart插件:

  1. 初始化Nhost客户端

在你的main.dart或任何其他合适的位置初始化Nhost客户端。

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 初始化Nhost客户端
    final nhostClient = NhostClient(
      backendUrl: 'https://你的Nhost后端URL', // 替换为你的Nhost后端URL
    );

    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: AuthScreen(nhostClient: nhostClient),
    );
  }
}
  1. 创建认证屏幕

在你的项目中创建一个新的Dart文件,比如auth_screen.dart,并在其中定义你的认证逻辑。

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

class AuthScreen extends StatefulWidget {
  final NhostClient nhostClient;

  AuthScreen({required this.nhostClient});

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

class _AuthScreenState extends State<AuthScreen> {
  final _formKey = GlobalKey<FormState>();
  String? email;
  String? password;
  String? errorMessage;

  void _register() async {
    try {
      await widget.nhostClient.auth.register(email: email!, password: password!);
      setState(() {
        errorMessage = null;
      });
      // 用户注册成功后,可以跳转到其他页面或显示成功信息
      print('User registered successfully');
    } catch (e) {
      setState(() {
        errorMessage = e.toString();
      });
    }
  }

  void _login() async {
    try {
      await widget.nhostClient.auth.login(email: email!, password: password!);
      setState(() {
        errorMessage = null;
      });
      // 用户登录成功后,可以跳转到其他页面或显示成功信息
      print('User logged in successfully');
    } catch (e) {
      setState(() {
        errorMessage = e.toString();
      });
    }
  }

  void _logout() async {
    try {
      await widget.nhostClient.auth.logout();
      // 用户注销成功后,可以更新UI或显示注销成功信息
      print('User logged out successfully');
    } catch (e) {
      print(e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Auth Screen'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Form(
              key: _formKey,
              child: Column(
                children: [
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Email'),
                    onSaved: (value) => email = value,
                  ),
                  TextFormField(
                    decoration: InputDecoration(labelText: 'Password'),
                    obscureText: true,
                    onSaved: (value) => password = value,
                  ),
                ],
              ),
            ),
            SizedBox(height: 16),
            ElevatedButton(
              onPressed: _register,
              child: Text('Register'),
            ),
            SizedBox(height: 8),
            ElevatedButton(
              onPressed: _login,
              child: Text('Login'),
            ),
            if (widget.nhostClient.auth.isAuthenticated) {
              SizedBox(height: 16),
              ElevatedButton(
                onPressed: _logout,
                child: Text('Logout'),
              ),
            }
          ],
        ),
      ),
      if (errorMessage != null) {
        bottomSheet: BottomSheet(
          onClosing: () => setState(() => errorMessage = null),
          builder: (context) => Padding(
            padding: EdgeInsets.all(16),
            child: Text(errorMessage!, style: TextStyle(color: Colors.red)),
          ),
        ),
      },
    );
  }
}

这个示例展示了如何使用nhost_auth_dart插件进行用户注册、登录和注销的基本流程。在实际应用中,你可能需要根据自己的需求进一步定制和扩展这个示例。

回到顶部