Flutter集成SharedPreferences遇_InternalLinkedHashMap类型不匹配异常求助
Hey there! Let's fix that annoying SharedPreferences error you're running into. That type mismatch exception (_InternalLinkedHashMap<dynamic, dynamic> not being a subtype of Map<String, Object>) is super common, and usually boils down to plugin version mismatches or cached project data. Here's how to sort it out:
First, let's break down why this happens: The error pops up because the SharedPreferences plugin is trying to convert a dynamically typed map to a Map<String, Object>, but something's getting stuck—either the plugin version doesn't play nice with your Flutter/Dart setup, or old cached data is messing with the type parsing.
1. Update SharedPreferences to the latest stable version
Head over to your project's pubspec.yaml file, find the shared_preferences dependency line, and bump it to the newest stable version. For example:
dependencies: flutter: sdk: flutter shared_preferences: ^2.2.2 # Replace with the latest stable compatible version
Then run this in your terminal to update the dependency:
flutter pub get
2. Clear project cache and restart your IDE
Old cached files can sometimes cause weird type issues. Run these commands to wipe the cache and refresh dependencies:
flutter clean flutter pub get
After that, close and reopen your IDE—this ensures any cached type info gets reset.
3. Clear app storage (if the above doesn't work)
If you still see the error, it might be because some old, incorrectly typed data is stored in SharedPreferences on your device. Go to your phone's Settings > Apps > [Your App] > Storage, then tap "Clear Data". This will wipe any saved preferences, and let your app start fresh with the correct data types.
Quick tweak to your code (for null safety)
Looking at your AuthManager.init() code, since you're a beginner, it's a good idea to embrace Dart's null safety here. Just update the variable declarations to use nullable types:
Future init() async { SharedPreferences prefs = await SharedPreferences.getInstance(); String? username = prefs.getString(KEY_USERNAME); String? oauthToken = prefs.getString(KEY_OAUTH_TOKEN); if (username == null || oauthToken == null) { _loggedIn = false; await logout(); } else { _loggedIn = true; _username = username; } _initialized = true; }
This makes your code more explicit and aligns with modern Dart practices, which can help avoid similar type issues down the line.
内容的提问来源于stack exchange,提问作者ASP

