此表达式的类型为“void”,因此无法使用其值- Flutter

axr492tv  于 2023-01-31  发布在  Flutter
关注(0)|答案(1)|浏览(169)
import 'package:demo_app/services/api.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';

class AuthProvider extends ChangeNotifier{
  bool isAuthenticated = false;
  late String token;
  late ApiService apiService;

  AuthProvider() {
    init();
  }

  Future<void> init() async {
    token = await getToken();
    if (token.isNotEmpty) {
      isAuthenticated = true;
    }
    apiService = ApiService(token);
    notifyListeners();
  }

  Future<void> register(String name, String email, String password, String passwordConfirm, String deviceName) async{
  token = await apiService.register(name, email, password, passwordConfirm, deviceName);
  isAuthenticated = true;
  setToken();
  notifyListeners();
  }

  Future<void> logIn(String email, String password, String deviceName) async{
  token = await apiService.login(email, password, deviceName);
  isAuthenticated = true;
  setToken();    
  notifyListeners();
  }

  Future<void> logOut() async{
  token = '';
  isAuthenticated = false;
  setToken();  
  notifyListeners();
  }

  Future<void> setToken() async{
    final pref = await SharedPreferences.getInstance();
    pref.setString('token', token);
  }

  Future<void> getToken() async{
    final pref = await SharedPreferences.getInstance();
    pref.getString('token') ?? '';
  }

}
    • 令牌=等待获取令牌();**

给出此错误
此表达式的类型为"void",因此无法使用其值。请尝试检查是否使用了正确的API;可能有一个函数或调用返回了你不期望的void。还要检查类型参数和变量,它们也可能是void。
解决这个问题有什么线索吗?

arknldoa

arknldoa1#

请尝试以下代码:

Future<void> init() async {
  token = await getToken();
  if (token.isNotEmpty) {
    isAuthenticated = true;
  }
  apiService = ApiService(token);
  notifyListeners();
}
Future<String> getToken() async {
  final pref = await SharedPreferences.getInstance();
  final token = pref.getString("token") ?? "";
  return token;
}

相关问题