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

