jesway / flutter_translate Goto Github PK
View Code? Open in Web Editor NEWFlutter Translate is a fully featured localization / internationalization (i18n) library for Flutter.
License: MIT License
Flutter Translate is a fully featured localization / internationalization (i18n) library for Flutter.
License: MIT License
The screen flashes black when loading the delegate. I've looked into this issue, but don't think it is related.
This can be replicated by running the example app and noticing the color flash between the splash image ending and the main app content loading.
Any idea on how to resolve this? I've been looking into it for a while now.
E/flutter (10632): [ERROR:flutter/lib/ui/ui_dart_state.cc(166)] Unhandled Exception: Unable to load asset: assets/i18n/en.json
E/flutter (10632): #0 PlatformAssetBundle.load (package:flutter/src/services/asset_bundle.dart:223:7)
E/flutter (10632):
E/flutter (10632): #1 AssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:69:33)
E/flutter (10632): #2 CachingAssetBundle.loadString. (package:flutter/src/services/asset_bundle.dart:164:56)
E/flutter (10632): #3 _LinkedHashMapMixin.putIfAbsent (dart:collection-patch/compact_hash.dart:291:23)
E/flutter (10632): #4 CachingAssetBundle.loadString (package:flutter/src/services/asset_bundle.dart:164:27)
E/flutter (10632): #5 LocaleFileService.getLocaleContent (package:flutter_translate/locale_file_service.dart:25:33)
E/flutter (10632): #6 LocaleService.getLocaleContent (package:flutter_translate/locale_service.dart:31:47)
E/flutter (10632): #7 LocalizationDelegate.changeLocale (package:flutter_translate/localization_delegate.dart:34:52)
E/flutter (10632): #8 LocalizationDelegate._loadDeviceLocale (package:flutter_translate/localization_delegate.dart:124:23)
E/flutter (10632):
E/flutter (10632): #9 LocalizationDelegate.create (package:flutter_translate/localization_delegate.dart:86:28)
E/flutter (10632):
E/flutter (10632): #10 main (package:my_app/main.dart:34:47)
E/flutter (10632): #11 _runMainZoned.. (dart:ui/hooks.dart:233:25)
E/flutter (10632): #12 _rootRun (dart:async/zone.dart:1190:13)
E/flutter (10632): #13 _CustomZone.run (dart:async/zone.dart:1093:19)
E/flutter (10632): #14 _runZoned (dart:async/zone.dart:1630:10)
E/flutter (10632): #15 runZonedGuarded (dart:async/zone.dart:1618:12)
E/flutter (10632): #16 _runMainZoned. (dart:ui/hooks.dart:225:5)
E/flutter (10632): #17 _startIsolate. (dart:isolate-patch/isolate_patch.dart:301:19)
E/flutter (10632): #18 _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:168:12)
E/flutter (10632):
do we need to translate all text in json files and then call them?
or is there any dynamic translation available...
please help...
Hi, have plan to add null safety to this package soon? It is preventing me from upgrading. Thanks!
I notice some localization library for Flutter supports naming like languageCode-countryCode
(for example en-US
, en-UK
) but this library doesn't. Can you add support for it?
I notice the font size of the Text change a little bit when I am changing locale from en to zh_HK on iOS. The font is smaller in en comparing to zh_HK.
Even the text that is not translate behave like this. For example 'Hello', is bigger when my locale is set to zh_HK and become smaller when changing locale to en.
Any ideas?
We are using flutter_translate in our project.
We have a library and multiple apps that use the library. Both contain strings that we want internationalized, so we have translation files in both
library_pkg/assets/i18n
app_pkg1/assets/i18n
What is the correct way to setup such a project?
Problem: when you test your app with Flutter Drive - app will stay on White screen while trying to init the app.
To be more specific, this call is never executes:
final delegate = await LocalizationDelegate.create(fallbackLocale: 'en_US', supportedLocales: ['en_US']);
Root cause of the issue is inside locale_file_service.dart - Future getLocaleContent(String file) method.
This code hangs:
return rootBundle.loadString(file);
This code will work:
static Future<String> getLocaleContent(String file) async
{
final ByteData data = await rootBundle.load(file);
if (data == null) return null;
return utf8.decode(data.buffer.asUint8List());
}
Underlying reason for that (if qurious to read) is here:
flutter/flutter#24703
Has your project web-support? I assumed it as it is a "web" project on pub.dev but I didn't get it to work 😞 The app doesn't seem to start and stays white in Chrome. I've even reproduced it with your example project:
flutter channel dev
flutter upgrade
flutter config --enable-web
cd example
flutter create .
flutter run -d chrome
Cheers, Dennis
I have to restart the android app to notice the system language change. On ios the app will be automatically rebuild.
Any ideas to solve this?
This package uses single braces to escape arguments in translation strings:
{
"message": "Hello {name}!"
}
Most other similar translation libraries (eg ngx-translate, i18next) use double braces to escape:
{
"message": "Hello {{name}}!"
}
We are using flutter_translate
in our Flutter app, and ngx-translate
in our Web app. We would really like to consolidate our translation strings so they are shared between both projects, as this will help ensure messages are consistent across platforms and reduce costs of translating to other languages.
I'm wondering if a good approach would be to allow customising the argument escape characters, so we could use double-braces in our project. For backwards compatibility, we would default to the current single brace behaviour. Perhaps set the escape characters as optional parameters to Localization.load
:
class Localization
{
static void load(Map<String, dynamic> translations, {openingEscapeString = '{', closingEscapeString = '}'})
{
instance._translations = translations;
instance._openingEscapeString = openingEscapeString;
instance._closingEscapeString = closingEscapeString;
}
}
I'm happy to do the work to support this, would just like some feedback on the approach.
Cheers!
i saved current lang in SharedPreferences key
when app start i get this key and want to set this as my current local
i tray with main method
String currentLang=await AppUtil.currentLang();
var delegate = await LocalizationDelegate.create(
fallbackLocale:currentLang !=null && currentLang != "" ? currentLang : 'en_US',
supportedLocales: ['en_US', 'ar']);
but not work as expected
I follow the guide to configure the flutter_translate:
void main() async
{
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'en_US',
supportedLocales: ['en_US', 'es', 'fa']);
runApp(LocalizedApp(delegate, MyApp()));
}
It takes about 263ms (debug build, Galaxy S9 Android 10) to create the LocalizationDelegate
. Thus, I wonder if you have another way to lazy create it?
For example: let runApp(myApp())
first, then show a loading screen while waiting for creating the LocalizationDelegate
. After it's done, then show the next screen.
That idea is borrowed from GetIt > allReady method. I'm not sure if you can apply that into flutter_translate.
Library info:
flutter_translate: ^1.4.0
Flutter (Channel stable, v1.12.13+hotfix.8, on Microsoft Windows [Version 10.0.17763.1098], locale en-US)
Finally, thanks for your great library. I'm using it in all 4 projects. 💯
I have a dynamic list showing some descriptions like this:
List<Map> descriptions = [
"title": "My title",
"description": ["description1", "description2"]
];
How could I get this from the translation json file?
Can you give me an example, Other package is already used ?
part of 'keys.dart';
// **************************************************************************
// Generator: FlutterTranslateGen
// **************************************************************************
class Keys {
static const String App_Bar_Title = 'app_bar.title';
static const String Button_Cancel = 'button.cancel';
static const String Button_Change_Language = 'button.change_language';
static const String Language_Name_En = 'language.name.en';
static const String Language_Name_Es = 'language.name.es';
static const String Language_Name_Fa = 'language.name.fa';
static const String Language_Selected_Message = 'language.selected_message';
static const String Language_Selection_Message = 'language.selection.message';
static const String Language_Selection_Title = 'language.selection.title';
static const String Plural_Demo = 'plural.demo';
}`
de.json:
{ "app_bar": { "title": "Willkommen auf der Homepage" }, "button": { "cancel": "Abbrechen", "change_language": "Sprache ändern" }, "language": { "name": { "en": "English", "es": "Spanisch", "fa": "Persisch" }, "selected_message": "Derzeit ausgewählte Sprache ist {language}", "selection": { "message": "Bitte wählen Sie eine Sprache aus der Liste", "title": "Sprachauswahl" } }, "plural": { "demo": { "0": "Bitte drücken Sie die 'Plus'-Taste.", "1": "Sie haben den Knopf einmal gedrückt.", "else": "Sie haben den Knopf {{value}} mal gedrückt." } } }
ru.json:
{ "app_bar": { "title": "Добро пожаловать на домашнюю страницу" }, "button": { "cancel": "отмена", "change_language": "Изменить язык" }, "language": { "name": { "en": "Английский", "es": "Испанский", "fa": "Персидский" }, "selected_message": "Текущий выбранный язык {language}", "selection": { "message": "Пожалуйста, выберите язык из списка", "title": "Выбор языка" } }, "plural": { "demo": { "0": "Пожалуйста, начните нажимать кнопку «плюс»", "1": "Вы нажали кнопку один раз.", "else": "Вы нажали кнопку {{value}} раз." } } }
I have Polish language turned on, but the buttons are in English
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'pl',
supportedLocales: ['pl'],
);
runApp(LocalizedApp(delegate, MyApp()));
and
@override
Widget build(BuildContext context) {
var localizationDelegate = LocalizedApp.of(context).delegate;
.....
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
locale: localizationDelegate.currentLocale,
}
Reference:
flutter/flutter#14128
The latest version of flutter_device_locale, which is a dependency of this project cannot be installed:
Jesway/flutter_device_locale#1
0.3.2 is currently not installable, but there is a PR to fix the issue.
Making a note here in case anybody else runs into this problem - a workaround for now is to explicitly add 0.3.1 to your project's pubspec.yml:
flutter_device_locale: 0.3.1
Until this upstream issue has been fixed
Issue: This package depends on flutter_device_locale 0.4.0 which depends on plugin_platform_interface version 1.0.1 which is very old as there is version 2.0.0 available. So when I am trying to add crashlytics to my project which has the latest 2.0.0 version as dependency, the version resolving is getting failed. Please fix this as soon as possible.
Add an option to automatically sync the current locale with the system locale.
So when the system locale is changed, the current/app locale will be reloaded as well (if supported).
Reference: #20
How could I translate something like this in my json?
"test": {
"test1": "hi"
},
Hello. I try to use another path for my localization files
var delegate = await LocalizationDelegate.create(
...
basePath: '/data/user/0/com.example.app/app_flutter/i18Sources/'
...
supportedLocales: [
'en_EN',
'pt_PT',
'pt_BR',
]
but I still have this Unhandled Exception: Unable to load asset: /data/user/0/com.example.app/app_flutter/i18Sources/en.json
Is there any way to use localization files outside of the assets folder?
I use your latest version in our app (flutter_translate: ^1.6.0) but can't build for macOS or Windows due to lack of support by your package.
With the new release of Flutter 2.0.0 where desktop support is in beta and possibly stable channels, support for desktop is really important.
Hi,
In Android, when a project have multiple flavours, the system will bundle toghether all strings, based on the current build.
So with this configuration:
If I compile the dev
flavour, the strings usable are the ones from main
+ dev
.
If there is a string called app_name
in main
, and it is also present in dev
, then the dev
one overrides the main
one.
I would like to have a similar feature for flutter_translate
. Even if there is not the concept of flavours for dart code, the same thing can be recreated using environment variables or something similar.
I think that something like: delegate.loadFlavour('dev')
could do the trick.
maybe with something like this in the asset folder:
What do you think?
When adding ar local and adding the language json file it fall down to default local
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'en_US',
supportedLocales: ['en_US', 'es', 'ar']);
How to force layout to be RTL in a language?
Hey there,
First of all thank you for this package it is great and was really helpful when refactoring the localizations for one of my projects. I tried a few different localization packages and this one was definitely the best and easiest to use.
I spent a couple of hours trying to figure out Chinese localization today(Simplified and Traditional). I also ended up cloning the flutter_device_locale
package and testing it out on an iOS and Android simulator.
For iOS I found that:
getCurrentLocale
would return zh_HansgetCurrentLocale
would return zh_HantFor Android I found that:
getCurrentLocale
would return zh_CNgetCurrentLocale
would return zh_TWWhat I want to know is, will I have to make 4 translation files to support all of these situations(zh_Hans.json, zh_Hant.json, zh_CN.json, zh_TW.json)? Or is there some other way, like using localeResolutionCallback
, to only use two files(ex: only zh_Hans.json and zh_Hant.json) and force one of the platforms(iOS or Android) to follow that specific pattern?
Thanks again for this awesome package!
Package version: 1.6.0
[√] Flutter (Channel beta, 1.18.0-11.1.pre, on Microsoft Windows [Version 10.0.18363.836], locale es-ES)
• Flutter version 1.18.0-11.1.pre at C:\src\flutter-beta
• Framework revision 2738a1148b (2 weeks ago), 2020-05-13 15:24:36 -0700
• Engine revision ef9215ceb2
• Dart version 2.9.0 (build 2.9.0-8.2.beta)
[√] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
• Android SDK at C:\Users\Matias\AppData\Local\Android\Sdk
• Platform android-29, build-tools 29.0.3
• ANDROID_HOME = C:\Users\Matias\AppData\Local\Android\Sdk
• Java binary at: C:\Program Files\Android\Android Studio\jre\bin\java
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
• All Android licenses accepted.
[√] Chrome - develop for the web
• Chrome at C:\Program Files (x86)\Google\Chrome\Application\chrome.exe
[√] Android Studio (version 3.6)
• Android Studio at C:\Program Files\Android\Android Studio
• Flutter plugin version 45.1.1
• Dart plugin version 192.8052
• Java version OpenJDK Runtime Environment (build 1.8.0_212-release-1586-b04)
[√] VS Code
• VS Code at C:\Users\Temp\AppData\Local\Programs\Microsoft VS Code
• Flutter extension version 3.11.0
[√] Connected device (3 available)
• WAS LX1A • H3XDU17929008760 • android-arm64 • Android 8.0.0 (API 26)
• Web Server • web-server • web-javascript • Flutter Tools
• Chrome • chrome • web-javascript • Google Chrome 83.0.4103.61
When this package is generated at generated_plugin_registrant.dart
. I get a info warning the lint rule implementation_imports
Don't import implementation files from another package
You may need some changes in imports and code to fix this info warning
I am using this package for splash screen "flutter_native_splash"
Is this have to do with main being synch?
EDIT: the bug is from "flutter_native_splash"
I keep receiving this message when i run my program. if i add
flutter:
assets:
then i receive message No file or variants found for asset: assets/i18n.
Please update the document to handle unit test.
When you run this library on iOS with xcode 12.1 and above, it says build_run done, but it crashes, soon as the app boots up, and the interesting thing is that it doesn't give you any errors, I tried the example you provided in the repository and it behaves exactly the same way, any suggestions on why this happens nis appreciated in advance.
Below is the result of flutter doctor:
[✓] Flutter (Channel stable, 1.22.2, on Mac OS X 10.15.7 19H2, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 30.0.0)
[✓] Xcode - develop for iOS and macOS (Xcode 12.1)
[✓] Android Studio (version 4.1)
[!] Connected device
! No devices available
When testing a widget the _translations
map is passed as null and throws a exception. It's possible to wrap the widget in a LocalizedApp
widget and configure the localization, but I believe that testing a single widget should be more straightforward. Am I missing something here?
Example error:
The following NoSuchMethodError was thrown building ExpiredProductButton(dirty):
The method 'containsKey' was called on null.
Receiver: null
Tried calling: containsKey("mission")
Hello Team
Greetings of the Day!!
i have integrate the localisation in application, Its integrated successfully, but when i try to change the language then it's not translated
Can you please tell me how i can resolve it
I am change the language from other screen, like from profile screen..
Here is my main.dart code
import 'dart:ui';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter_translate/flutter_translate.dart';
import 'Home.dart';
final GlobalKey navigatorKey = GlobalKey(debugLabel: "Main Navigator");
Future main() async {
WidgetsFlutterBinding.ensureInitialized();
var delegate = await LocalizationDelegate.create(fallbackLocale: 'en_US', supportedLocales: ['en_US', 'ar']);
runApp(LocalizedApp(delegate,
new MaterialApp(
debugShowCheckedModeBanner: false,
navigatorKey: navigatorKey,
home: new MyApp()
),
),
);
}
class MyApp extends StatelessWidget {
@OverRide
Widget build(BuildContext context) {
var localizationDelegate = LocalizedApp.of(context).delegate;
new Future.delayed(const Duration(seconds: 10), () {
Navigator.pushReplacement(context, MaterialPageRoute(builder: (context) => Home()));
});
return LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: MaterialApp(
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
locale: localizationDelegate.currentLocale,
debugShowCheckedModeBanner: false,
theme: ThemeData(
backgroundColor: Color.fromARGB(1, 138, 51, 147),
),
home: Scaffold(
backgroundColor: Colors.white,
body: Container(
child: new Center(
child: new Image(image: new AssetImage('assets/images/logo.png'), fit: BoxFit.fill)
),
),
),
),
);
}
}
I'm seeing this error when I try to run the app with flutter 2.0.1
Flutter 2.0.1 • channel stable • https://github.com/flutter/flutter.git
Framework • revision c5a4b4029c (5 days ago) • 2021-03-04 09:47:48 -0800
Engine • revision 40441def69
Tools • Dart 2.12.0
Doctor summary (to see all details, run flutter doctor -v):
[✓] Flutter (Channel stable, 2.0.1, on macOS 11.2.2 20D80 darwin-x64, locale en-US)
[✓] Android toolchain - develop for Android devices (Android SDK version 29.0.3)
[✓] Xcode - develop for iOS and macOS
[✓] Chrome - develop for the web
[✓] Android Studio (version 4.1)
[✓] VS Code (version 1.54.1)
[✓] Connected device (3 available)
• No issues found!
ERROR
../../../flutter/.pub-cache/hosted/pub.dartlang.org/flutter_translate-1.5.7/lib/localized_app.dart:15:61: Error: The method 'ancestorWidgetOfExactType' isn't defined for the class 'BuildContext'.
- 'BuildContext' is from 'package:flutter/src/widgets/framework.dart' ('../../../flutter/packages/flutter/lib/src/widgets/framework.dart').
Try correcting the name to the name of an existing method, or defining a method named 'ancestorWidgetOfExactType'.
static LocalizedApp of(BuildContext context) => context.ancestorWidgetOfExactType(LocalizedApp);
when the method 'changeLocale' is called,how to update other pages
It's not working with flutter web. When I run without LocalizationProvider as parent widget the app opens in browser but with this I am getting white screen. I used flutter run -d chrome
to run the app.
First of all, thanks for this nice project :)
Currently translate('key')
returns the key
is it didn't find a translation, but would be nice to be able to specify a default value like
translate('my.key', def: 'Something');
Or have a function that returns null
so we can do:
translate('my.key') ?? 'Something';
Hi,
I would like to be able to set a "fallback" language for missing keys (not missing locales).
For example, having this situation:
en.json
{
"language": "English"
}
it.json
{
}
main.dart
delegate = await LocalizationDelegate.create(
fallbackLocale: 'en',
supportedLocales: ['it', 'en']);
When I open my app with the IT locale, I would like to see English
when I call translate('language')
Let me know if my request is feasible and clear. Thanks
I have a page which contains some bottom navigationbar item and in one page, I set the locale and the strings of current page changed except the appbar title and bottom navigationbar items. I have to click any of the navigationbar item, then it changed.
I simplify the code and make a demo on https://github.com/liudonghua123/redux_thunk_example/tree/flutter_translate.
It seems the same as using another translate package (easy_localization, aissat/easy_localization#108).
In many languages you have different forms of words depending on number of items.
Currently flutter_translate does only support:
"0"
"1"
"else"
can you please add other forms of plurals: "many", "few" etc?
for example:
in English you'd say:
0 departments
, 1 department, 2+ departments
but in Polish you'd say:
0 działów
, 1 dział
, 2-4 działy
, 5 działów
, 11 działów
, 12 działów
, 13 działów
, 22 działy
So you have different versions for 2-4, 22-24, 32-34, 42-44 and so on (yeah weird)
But such cases are in many other languages as well
Native flutter supports all these: https://api.flutter.dev/flutter/intl/Intl/plural.html
https://developer.mozilla.org/en-US/docs/Mozilla/Localization/Localization_and_Plurals
import 'package:flutter_localizations/flutter_localizations.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_translate/flutter_translate.dart';
void main() async {
var delegate = await LocalizationDelegate.create(
fallbackLocale: 'en_US',
supportedLocales: [
'en_US',
'es',
]);
runApp(LocalizedApp(delegate, MyApp()));
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
var localizationDelegate = LocalizedApp.of(context).delegate;
return LocalizationProvider(
state: LocalizationProvider.of(context).state,
child: MaterialApp(
title: 'Flutter Translate Demo',
localizationsDelegates: [
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
localizationDelegate
],
supportedLocales: localizationDelegate.supportedLocales,
//locale: localizationDelegate.currentLocale,
theme: ThemeData(primarySwatch: Colors.blue),
home: MyHomePage(),
),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
var localizationDelegate = LocalizedApp.of(context).delegate;
return Scaffold(
appBar: AppBar(
title: Text(translate('app_bar.title')),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(translate('language.selected_message', args: {
'language': translate(
'language.name.${localizationDelegate.currentLocale.languageCode}')
})),
RaisedButton(
onPressed: () {
changeLocale(context, 'en_US');
print(localizationDelegate.currentLocale.languageCode);
setState(() {});
},
child: Text('english'),
),
RaisedButton(
onPressed: () {
changeLocale(context, 'es');
print(localizationDelegate.currentLocale.languageCode);
setState(() {});
},
child: Text('español'),
),
],
),
),
);
}
}
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.