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

Flutter本地化系统失效,如何实现语言切换按钮并修复翻译功能?

Fixing Flutter Localization & Adding a Language Toggle Button

Hey there! Let's get your localization working and that language toggle button up and running. The main issue in your current code is that the MaterialApp's locale is hardcoded, so changing the locale variable in your MyHomePage doesn't actually update the app's active locale. Here's how to fix this step by step:

Step 1: Convert MyApp to a Stateful Widget

We need MyApp to manage the locale state so it can update when the button is pressed. Here's the updated code:

import 'package:final_translating_test/taylake.dart';
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'app_localizations.dart';
import 'dakmilprison.dart';
import 'damw.dart';

void main() {
 runApp(MyApp());
}

class MyApp extends StatefulWidget {
 @override
 _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
 // Track the current locale
 Locale _currentLocale = Locale('vi','VN');

 // Method to update the locale
 void changeLocale(Locale newLocale) {
   setState(() {
     _currentLocale = newLocale;
   });
 }

 @override
 Widget build(BuildContext context) {
 return MaterialApp(
 title: 'Flutter Demo',
 locale: _currentLocale, // Use the stateful locale instead of hardcoding
 debugShowCheckedModeBanner: false,
 routes: {
 '/1': (context) => TayLake(),
 '/2': (context) => DamW(),
 '/3': (context) => DakMilPrison(),
 },
 supportedLocales: [Locale('en', 'US'), Locale('vi', 'VN')],
 localizationsDelegates: [
 AppLocalizations.delegate,
 GlobalMaterialLocalizations.delegate,
 GlobalWidgetsLocalizations.delegate,
 ],
 localeResolutionCallback: (locale, supportedLocales) {
 for (var supportedLocale in supportedLocales) {
 if (supportedLocale.languageCode == locale!.languageCode && supportedLocale.countryCode == locale.countryCode) {
 return supportedLocale;
 }
 }
 return supportedLocales.first;
 },
 // Pass the locale change method to MyHomePage
 home: MyHomePage(onLocaleChanged: changeLocale),
 );
 }
}

Step 2: Update MyHomePage to Use the Locale Callback

Now modify your MyHomePage to accept the locale change callback and trigger it when the translate button is pressed. We'll also clean up the variable names for clarity:

class MyHomePage extends StatefulWidget {
 final Function(Locale) onLocaleChanged; // Callback to update locale

 MyHomePage({
 Key? key,
 required this.onLocaleChanged,
 }) : super(key: key);

 @override
 _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
 bool _isVietnamese = true; // Clearer variable name than _isClicked

 @override
 Widget build(BuildContext context) {
 return Scaffold(
 body: Column(
 children: [
 Stack(
 children: [
 Image.network(
 'https://t4.ftcdn.net/jpg/03/36/07/85/240_F_336078503_3rIlo0PPrbrxyPbR99qXVo6VATqWsHvl.jpg',
 filterQuality: FilterQuality.high,
 fit: BoxFit.fitWidth,
 width: 500,
 ),
 ListTile(
 leading: Icon(Icons.menu_outlined, color: Colors.white, size: 30),
 trailing: IconButton(
 onPressed: () {
 setState(() {
 _isVietnamese = !_isVietnamese;
 });
 // Trigger the locale change
 widget.onLocaleChanged(
 _isVietnamese ? Locale('vi', 'VN') : Locale('en', 'US'),
 );
 },
 icon: Icon(Icons.translate_outlined ,size: 15.0),
 ),
 ),
 ],
 ),
 Expanded(
 child: PageView(
 children: <Widget>[
 placeButton(
 context, 
 // Make sure you're fetching the translated text correctly
 AppLocalizations.of(context)!.translate("titleHoTay"), 
 "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRLRsM_lVQtJSMBRgTzeyPIrqdeMFV7M3gCzA&usqp=CAU", 
 "/1"
 ),
 placeButton(
 context, 
 AppLocalizations.of(context)!.translate("titleDapW"), 
 "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTabeU7lO71WhEE3EY99nU087Xwlj5PAPd76g&usqp=CAU", 
 "/2"
 ),
 placeButton(
 context, 
 AppLocalizations.of(context)!.translate("titleNhaNgucDm"), 
 "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSzl8XkPISxI0Uqcy0FR6g3cRvtng1Ghu6T9w&usqp=CAUs", 
 "/3"
 )
 ],
 ),
 ),
 ],
 ),
 );
 }
}

Key Notes to Ensure Everything Works:

  • Double-check that your AppLocalizations class is correctly loading translation files from your assets (per the tutorial you followed). Make sure your pubspec.yaml has the assets configured properly.
  • When you call AppLocalizations.of(context)!.translate(key), ensure the keys match exactly what's in your JSON translation files.
  • The setState in _MyAppState will rebuild the MaterialApp with the new locale, which triggers all localized text in your app to update automatically.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 04:22:45