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

Dart项目运行报错:getter 'loggedUserName'的返回类型Future<String>与setter的String类型不兼容

Fixing the Getter/Setter Type Mismatch in Dart

Hey there! Let's break down and fix this error you're hitting. The core issue here is that your getter loggedUserName returns a Future<String> (since it's async), but your setter expects a plain String—Dart requires getter and setter types to be compatible, which is why you're seeing the getter_not_assignable_setter_types error.

Why This Happens

Dart setters can't be asynchronous (they can't return a Future), but your getter has to be async because accessing SharedPreferences is an asynchronous operation. This creates a direct type mismatch between the getter's return value and the setter's input type.

The Clean Solution

Since we can't make a setter async, the best fix is to replace the setter with an asynchronous method instead. Here's how to adjust your code:

// Keep the async getter (add a default value to avoid returning null)
static Future<String> get loggedUserName async { 
  final prefs = await SharedPreferences.getInstance(); 
  return prefs.getString(LOGGED_USERNAME_KEY) ?? ''; 
} 

// Replace the setter with an async method
static Future<void> setLoggedUserName(String userName) async { 
  final prefs = await SharedPreferences.getInstance(); 
  await prefs.setString(LOGGED_USERNAME_KEY, userName); 
}

How to Use the Updated Code

Now when you need to set or get the username, you'll use await for both operations to handle the asynchronous flow:

// Setting the username
await YourClassName.setLoggedUserName('Carlos');

// Getting the username
String currentUser = await YourClassName.loggedUserName;

Why This Works

By using an async method instead of a setter, we're working with Dart's rules around asynchronous operations. The getter remains async (since it needs to wait for SharedPreferences to initialize), and the set method is also async so we can properly wait for the save operation to finish—this avoids potential race conditions where you might try to read the value before it's been saved.

内容的提问来源于stack exchange,提问作者Carlos Henrique Biazin Esteves

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 01:07:43