我如何在颤振中使用 SharedPreferences?

时间:2020-12-19 16:38:52

标签: firebase flutter dart google-signin

我正在尝试让 GoogleSign 与一个 web 应用程序一起工作,为此我一直在关注一篇文章。这是他们所说的用于登录的功能:

Future<String> signInWithGoogle() async {
  // Initialize Firebase
  await Firebase.initializeApp();

  final GoogleSignInAccount googleSignInAccount = await googleSignIn.signIn();
  final GoogleSignInAuthentication googleSignInAuthentication =
      await googleSignInAccount.authentication;

  final AuthCredential credential = GoogleAuthProvider.credential(
    accessToken: googleSignInAuthentication.accessToken,
    idToken: googleSignInAuthentication.idToken,
  );

  final UserCredential userCredential =
      await _auth.signInWithCredential(credential);
  final User user = userCredential.user;

  if (user != null) {
    // Checking if email and name is null
    assert(user.uid != null);
    assert(user.email != null);
    assert(user.displayName != null);
    assert(user.photoURL != null);

    uid = user.uid;
    name = user.displayName;
    userEmail = user.email;
    imageUrl = user.photoURL;

    assert(!user.isAnonymous);
    assert(await user.getIdToken() != null);

    final User currentUser = _auth.currentUser;
    assert(user.uid == currentUser.uid);

    SharedPreferences prefs = await SharedPreferences.getInstance();
    prefs.setBool('auth', true);

    return 'Google sign in successful, User UID: ${user.uid}';
  }

  return null;
}

它说 SharedPreferences 是一个未定义的类。这有什么作用?有必要吗?如果是,我该如何解决这个问题?非常感谢您的帮助,因为这是我第一次在 Flutter web 中使用 google 登录。

2 个答案:

答案 0 :(得分:1)

  1. 打开pubspec.yaml
  2. shared_preferences: ^0.5.12+4下方添加dependencies:
  3. 运行flutter pub get
  4. import 'package:shared_preferences/shared_preferences.dart';

这里是链接 https://pub.dev/packages/shared_preferences/install

答案 1 :(得分:0)

在您的 pubspec.yaml 文件中添加共享首选项依赖项。

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.0
  shared_preferences: ^0.5.12+4

现在运行 flutter pug get。 像这样在文件中导入包后,

import 'package:shared_preferences/shared_preferences.dart';

现在应该可以正常工作了。