Flutter:如何从SharedPreferences获取语言值并保存到变量?
getPreferredLocale() (a Future) Hey there! I totally get why you're seeing that Instance of 'Future<Locale>' output—because getPreferredLocale() returns a Future, which represents an asynchronous operation that hasn't finished yet. You can't just assign or print it directly; you need to wait for the Future to resolve to get the actual Locale value.
Here are two common, easy ways to do this:
1. Use async/await (Most Readable)
This is the cleanest approach for most cases. You just need to wrap your call in an async function and use the await keyword to wait for the Future to complete:
// Create an async function to handle the operation Future<void> loadAndStoreLocale() async { // Initialize your preferences class final translatePrefs = TranslatePreferences(); // Wait for the Future to get the actual Locale value final Locale? userLocale = await translatePrefs.getPreferredLocale(); // Now you can save this value to a variable and use it! if (userLocale != null) { print(userLocale); // This will print something like Locale('es', 'ES') instead of the Future instance // Do whatever you need with userLocale here (pass to other pages, update UI, etc.) } else { print("No saved locale found—using default"); } }
Important Notes:
- You can only use
awaitinside a function marked withasync. - If you're calling this from your
main()function, make sure to initialize Flutter's binding first:void main() async { WidgetsFlutterBinding.ensureInitialized(); await loadAndStoreLocale(); runApp(MyApp()); } - If you're using this in a widget, call the async function from
initState()(sinceinitStatecan't be async itself, you'll call a separate async method):class MyHomePage extends StatefulWidget { @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { Locale? _savedLocale; @override void initState() { super.initState(); _loadLocale(); } Future<void> _loadLocale() async { _savedLocale = await TranslatePreferences().getPreferredLocale(); setState(() {}); // Update the UI if needed after loading } @override Widget build(BuildContext context) { return Scaffold( body: _savedLocale != null ? Text("Saved locale: ${_savedLocale!.languageCode}") : Text("Loading locale..."), ); } }
2. Use the then() Callback
If you prefer a more functional style, you can use the then() method on the Future to handle the result once it's ready:
void getLocaleWithThen() { final translatePrefs = TranslatePreferences(); translatePrefs.getPreferredLocale().then((Locale? locale) { // This code runs when the Future completes if (locale != null) { print(locale); // Save locale to a variable or use it here } }); }
Why Your Original Print Didn't Work?
When you called print(TranslatePreferences().getPreferredLocale());, you were printing the Future object itself (which is just a placeholder for the upcoming result), not the actual Locale value that the Future will eventually return. Using await or then() lets you access the resolved value once the async operation (reading from SharedPreferences) finishes.
内容的提问来源于stack exchange,提问作者Micipsa

