且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何存储用户ID或“密钥"?登录并从Flutter应用程序中的任何位置访问后?

更新时间:2023-12-04 11:23:16

我想您最终将希望通过超时进行用户身份验证,因此需要一种方法来在用户超时时通知应用程序.一个很好的方法是使用 ChangeNotifierProvider -有很好的教程,例如简单的应用程序状态管理.使用此机制来共享您的状态是一个好主意,甚至在您需要通知之前.

I guess you will eventually want to have user authentication with timeout, so will need a way to notify the app when the user times out. A good way to do this is using ChangeNotifierProvider - there are good tutorials, e.g. Simple app state management. It is a good idea to use this mechanism to share your state, even before you need notifications.

这是示例代码:

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

// User class
class User {
  final String username;
  User(this.username);
  String toString() => username;
}

// AuthService has all authentication logic, notifies listeners
class AuthService with ChangeNotifier {
  User _user;
  User get user => _user;

  Future<void> _authenticate(String email, String password,
      [String name]) async {
    // This is where you authenticate or register the user, and update the state
    _user = User("dummy");
    return Future<void>(() {});
  }

  Future<void> register(String name, String email, String password) async {
    return _authenticate(email, password, name);
  }

  Future<void> login(String email, String password) async {
    return _authenticate(email, password);
  }

  Future<void> logout() async {
    _user = null;
    notifyListeners();
    return Future<void>(() {});
  }
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Put all your ChangeNotifierProviders above MaterialApp
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => AuthService(),
        ),
      ],
      child: MaterialApp(
        title: 'Test App',
        theme: ThemeData(
          primarySwatch: Colors.blue,
        ),
        home: AuthTest(),
      ),
    );
  }
}

class AuthTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Center(
      child: Column(mainAxisAlignment: MainAxisAlignment.center, children: [
        // Login user
        TextButton(
          child: Text("Login"),
          onPressed: () async {
            await Provider.of<AuthService>(context, listen: false)
                .login("email", "password");
          },
        ),
        // Logout user
        TextButton(
          child: Text("Logout"),
          onPressed: () async {
            await Provider.of<AuthService>(context, listen: false).logout();
          },
        ),
        // Child form
        TextButton(
          child: Text("Form"),
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => AuthFormTest()),
            );
          },
        ),
      ]),
    );
  }
}

class AuthFormTest extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Get AuthService, will rebuild when it notifies listeners
    var authService = Provider.of<AuthService>(context);
    return Scaffold(
      appBar: AppBar(
        title: Text('User'),
      ),
      body: Center(child: Text('User: ${authService.user}')),
    );
  }
}