You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中token = await getToken()报错:表达式类型为void无法使用

问题解决方法

错误的核心原因是getToken()方法存在两处问题:

  • 返回类型声明为Future<void>,说明该方法不会返回任何值
  • 方法内部没有return语句返回实际获取到的token值

只需修改getToken()方法即可解决问题:

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

// 修改后
Future<String> getToken() async{
  final pref = await SharedPreferences.getInstance();
  return pref.getString('token') ?? '';
}

修改说明:

  1. 将返回类型从Future<void>改为Future<String>,明确告知编译器该方法会返回一个字符串类型的Future对象
  2. 添加return关键字,返回从SharedPreferences中获取的token值,当token不存在时返回空字符串

修改完成后,token = await getToken();就能正常获取token值并完成赋值,原错误会消失。

以下是修改后的完整AuthProvider代码:

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);
  }

  // 修改后的getToken方法
  Future<String> getToken() async{
    final pref = await SharedPreferences.getInstance();
    return pref.getString('token') ?? '';
  }

}

内容的提问来源于stack exchange,提问作者zaster

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 18:15:37