Flutter: Internationlization not working from my end. What should I do?

1,357 views
Skip to first unread message

Niyazi Toros

unread,
May 17, 2018, 8:07:35 AM5/17/18
to Flutter Dev
I am trying to build small demo app to test Flutter internationalisation. I found https://github.com/anilcancakir/flutter-internationalization and try to test it. I am getting error that is in blow.

ERROR:
  • Launching lib/main.dart on Android SDK built for x86 in debug mode... Initializing gradle... Resolving dependencies... Running 'gradlew assembleDebug'... Built build/app/outputs/apk/debug/app-debug.apk (30.7MB). Installing build/app/outputs/apk/app.apk... I/FlutterActivityDelegate(22888): onResume setting current activity to this E/flutter (22888): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: E/flutter (22888): type '_InternalLinkedHashMap' is not a subtype of type 'Map' where E/flutter (22888): _InternalLinkedHashMap is from dart:collection E/flutter (22888): String is from dart:core E/flutter (22888):
  • Map is from dart:core E/flutter (22888): String is from dart:core E/flutter (22888): String is from dart:core E/flutter (22888):

import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

class DemoLocalizations {
 
DemoLocalizations(this.locale);

 
final Locale locale;

 
static DemoLocalizations of(BuildContext context) {
 
return Localizations.of<DemoLocalizations>(context, DemoLocalizations);
 
}

 
Map<String, String> _sentences;

 
Future<bool> load() async {
 
String data = await rootBundle.loadString('resources/lang/${this.locale.languageCode}.json');
 
this._sentences = json.decode(data);
 
return true;
 
}

 
String trans(String key) {
 
return this._sentences[key];
 
}
}

class DemoLocalizationsDelegate extends LocalizationsDelegate<DemoLocalizations> {
 
const DemoLocalizationsDelegate();

 
@override
 
bool isSupported(Locale locale) => ['tr', 'en'].contains(locale.languageCode);

 
@override
 
Future<DemoLocalizations> load(Locale locale) async {
 
DemoLocalizations localizations = new DemoLocalizations(locale);
 await localizations
.load();

 
print("Load ${locale.languageCode}");

 
return localizations;
 
}

 
@override
 
bool shouldReload(DemoLocalizationsDelegate old) => false;
}

class MyApp extends StatelessWidget {
 
@override
 
Widget build(BuildContext context) {
 
return new MaterialApp(
 supportedLocales
: [
 
const Locale('tr', 'TR'),
 
const Locale('en', 'US')
 
],
 localizationsDelegates
: [
 
const DemoLocalizationsDelegate(),
 
GlobalMaterialLocalizations.delegate,
 
GlobalWidgetsLocalizations.delegate
 
],
 localeResolutionCallback
: (Locale locale, Iterable<Locale> supportedLocales) {
 
for (Locale supportedLocale in supportedLocales) {
 
if (supportedLocale.languageCode == locale.languageCode || supportedLocale.countryCode == locale.countryCode) {
 
return supportedLocale;
 
}
 
}

 
return supportedLocales.first;
 
},
 title
: 'Flutter Internationalization',
 home
: new MyPage(),
 
);
 
}
}

class MyPage extends StatelessWidget {
 
@override
 
Widget build(BuildContext context) {
 
return new Scaffold(
 body
: new Center(
 child
: new Text(
 
DemoLocalizations.of(context).trans('hello_world')
 
),
 
),
 
);
 
}
}

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

Didier Boelens

unread,
May 17, 2018, 10:30:49 AM5/17/18
to Flutter Dev
Please have a look at the following url where there is a full explanation on this topic:  https://www.didierboelens.com/2018/04/internationalization---make-an-flutter-application-multi-lingual/ and the solution to your problem.

Niyazi Toros

unread,
May 17, 2018, 11:28:14 AM5/17/18
to Flutter Dev
Thanks Didier, This is best solution I found so far. It is more than perfect. The way of explanation is awesome. Kind Regards



17 Mayıs 2018 Perşembe 15:07:35 UTC+3 tarihinde Niyazi Toros yazdı:

Niyazi Toros

unread,
May 17, 2018, 12:30:57 PM5/17/18
to Flutter Dev
I have only error on application.dart file and I wrote a comment a link that you provided. Thanks.


17 Mayıs 2018 Perşembe 15:07:35 UTC+3 tarihinde Niyazi Toros yazdı:
I am trying to build small demo app to test Flutter internationalisation. I found https://github.com/anilcancakir/flutter-internationalization and try to test it. I am getting error that is in blow.

Eric Seidel

unread,
May 17, 2018, 12:33:46 PM5/17/18
to Niyazi Toros, Flutter Dev
This seems like a Dart 2 strong-mode error where one type of object is being assigned to a conflicting type of object:

"
  •  E/flutter (22888): [ERROR:topaz/lib/tonic/logging/dart_error.cc(16)] Unhandled exception: E/flutter (22888): type '_InternalLinkedHashMap' is not a subtype of type 'Map' where E/flutter (22888): _InternalLinkedHashMap is from dart:collection E/flutter (22888): String is from dart:core E/flutter (22888):
  • Map is from dart:core E/flutter (22888): String is from dart:core E/flutter (22888): String is from dart:core E/flutter (22888):"
Are you sure that's the whole error?  I would expect it to show you a line number to your Dart code where it's failing?

--
You received this message because you are subscribed to the Google Groups "Flutter Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to flutter-dev...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Niyazi Toros

unread,
May 17, 2018, 1:01:02 PM5/17/18
to Flutter Dev
Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running 'gradlew assembleDebug'...
compiler message: lib/application.dart:2:35: Error: Type 'Locale' not found.
compiler message: typedef void LocaleChangeCallback(Locale locale);
compiler message:                                   ^
compiler message: lib/application.dart:8:11: Error: Type 'Locale' not found.
compiler message: Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));
compiler message:           ^
compiler message: lib/main.dart:74:32: Error: A value of type 'dart.core::Iterable<invalid-type>' can't be assigned to a variable of type 'dart.core::Iterable<dart.ui::Locale>'.
compiler message: Try changing the type of the left hand side, or casting the right hand side to 'dart.core::Iterable<dart.ui::Locale>'.
compiler message:       supportedLocales: applic.supportedLocales(),
compiler message:                                ^
compiler message: lib/main.dart:102:30: Error: A value of type '(dart.ui::Locale) → dynamic' can't be assigned to a variable of type '(invalid-type) → void'.
compiler message: Try changing the type of the left hand side, or casting the right hand side to '(invalid-type) → void'.
compiler message:     applic.onLocaleChanged = onLocaleChange;
compiler message:                              ^
compiler message: lib/application.dart:8:64: Error: 'Locale' isn't a type.
compiler message: Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));
compiler message:                                                                ^^^^^^
compiler message: lib/application.dart:8:86: Error: Method not found: 'Locale'.
compiler message: Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));
compiler message:                                                                                      ^^^^^^
Compiler failed on /Users/niyazitoros/IdeaProjects/capitalbank/lib/main.dart

FAILURE: Build failed with an exception.

* Where:
Script '/Users/niyazitoros/flutter/packages/flutter_tools/gradle/flutter.gradle' line: 426

* What went wrong:
Execution failed for task ':app:flutterBuildDebug'.
> Process 'command '/Users/niyazitoros/flutter/bin/flutter'' finished with non-zero exit value 1

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUİLD FAILED in 4s
Finished with error: Gradle build failed: 1


Code:
typedef void LocaleChangeCallback(Locale locale);
class APPLIC {
// List of supported languages
final List<String> supportedLanguages = ['en','tr', 'el', 'ru'];

// Returns the list of supported Locales
Iterable<Locale> supportedLocales() => supportedLanguages.map<Locale>((lang) => new Locale(lang, ''));

// Function to be invoked when changing the working language
LocaleChangeCallback onLocaleChanged;

///
/// Internals
///
static final APPLIC _applic = new APPLIC._internal();

factory APPLIC(){
return _applic;
}

APPLIC._internal();
}

APPLIC applic = new

Didier Boelens

unread,
May 17, 2018, 1:47:09 PM5/17/18
to Flutter Dev
Could you please try to import "dart:ui" since Locale is part of this package?


On Thursday, May 17, 2018 at 2:07:35 PM UTC+2, Niyazi Toros wrote:

Niyazi Toros

unread,
May 17, 2018, 1:59:53 PM5/17/18
to Flutter Dev
Hi Didier I import the dart ui, but now I ma getting new error:

And here is the my main.dart part of the code:

1) ERROR and 2) MAIN.DART

1) ERROR:
Launching lib/main.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running 'gradlew assembleDebug'...
Built build/app/outputs/apk/debug/app-debug.apk (32.1MB).
Installing build/app/outputs/apk/app.apk...
I/FlutterActivityDelegate(30446): onResume setting current activity to this
I/flutter (30446): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter (30446): The following NoSuchMethodError was thrown building MyApp(dirty):
I/flutter (30446): The method 'text' was called on null.
I/flutter (30446): Receiver: null
I/flutter (30446): Tried calling: text("app_title")
I/flutter (30446): 
I/flutter (30446): When the exception was thrown, this was the stack:
I/flutter (30446): #0      Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:46:5)
I/flutter (30446): #1      MyApp.build (file:///Users/niyazitoros/IdeaProjects/capitalbank/lib/main.dart:75:40)
I/flutter (30446): #2      StatelessElement.build (package:flutter/src/widgets/framework.dart:3687:28)
I/flutter (30446): #3      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3634:15)
I/flutter (30446): #4      Element.rebuild (package:flutter/src/widgets/framework.dart:3487:5)
I/flutter (30446): #5      ComponentElement._firstBuild (package:flutter/src/widgets/framework.dart:3614:5)
I/flutter (30446): #6      ComponentElement.mount (package:flutter/src/widgets/framework.dart:3609:5)
I/flutter (30446): #7      Element.inflateWidget (package:flutter/src/widgets/framework.dart:2899:14)
I/flutter (30446): #8      Element.updateChild (package:flutter/src/widgets/framework.dart:2702:12)
I/flutter (30446): #9      RenderObjectToWidgetElement._rebuild (package:flutter/src/widgets/binding.dart:857:16)
I/flutter (30446): #10     RenderObjectToWidgetElement.mount (package:flutter/src/widgets/binding.dart:828:5)
I/flutter (30446): #11     RenderObjectToWidgetAdapter.attachToRenderTree.<anonymous closure> (package:flutter/src/widgets/binding.dart:774:17)
I/flutter (30446): #12     BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2214:19)
I/flutter (30446): #13     RenderObjectToWidgetAdapter.attachToRenderTree (package:flutter/src/widgets/binding.dart:773:13)
I/flutter (30446): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&RendererBinding&WidgetsBinding.attachRootWidget (package:flutter/src/widgets/binding.dart:662:7)
I/flutter (30446): #15     runApp (package:flutter/src/widgets/binding.dart:704:7)
I/flutter (30446): #16     main (file:///Users/niyazitoros/IdeaProjects/capitalbank/lib/main.dart:50:3)
I/flutter (30446): <asynchronous suspension>
I/flutter (30446): #17     _startIsolate.<anonymous closure> (dart:isolate/runtime/libisolate_patch.dart:279:19)
I/flutter (30446): #18     _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)
I/flutter (30446): ════════════════════════════════════════════════════════════════════════════════════════════════════
D/        (30446): HostConnection::get() New Host Connection established 0x9d119740, tid 30486
D/EGL_emulation(30446): eglMakeCurrent: 0x9b67bd40: ver 3 0 (tinfo 0x9d103300)
Syncing files to device Android SDK built for x86...


2) MAIN.DART

class MyApp extends StatelessWidget {

  // This widget is the root of your application.

  @override

  Widget build(BuildContext context) {

    return new MaterialApp(

      debugShowCheckedModeBanner: false,

      localizationsDelegates: [

        _localeOverrideDelegate,

        const TranslationsDelegate(),

        GlobalMaterialLocalizations.delegate,

        GlobalWidgetsLocalizations.delegate,

      ],

      supportedLocales: applic.supportedLocales(),

      title: (Translations.of(context).text('app_title')),

      home: new MyHomePage(title: (Translations.of(context).text('app_title'))),

    );

  }

}



And


// TODO: 4) _MyHomePageState Class

class _MyHomePageState extends State<MyHomePage> {


  @override

  void initState() {

    // TODO: implement initState

    super.initState();

    _localeOverrideDelegate = new SpecificLocalizationDelegate(null);

    applic.onLocaleChanged = onLocaleChange;


    this.getCurrencyJsonData();

  }


  onLocaleChange(Locale locale){

    setState((){

      _localeOverrideDelegate = new SpecificLocalizationDelegate(locale);

    });

  }


  Future<String> getCurrencyJsonData() async {

    var response = await http.get(

        Uri.encodeFull("https://secure.***********”),

        headers: {'Accept': 'application/json'});


    setState(() {

      var resBody = json.decode(response.body);

      currencyData = resBody[“currency”];

 

    });


    return "Success!";

  }



// TODO: BUILD WIDGET

  @override

  Widget build(BuildContext context) {

    if (currencyData == null){

      return new Center(

          child: new CircularProgressIndicator(

            backgroundColor: lightMainGreen

          )

      );

    } else {

      return new Scaffold(

        // APPBAR

        appBar: new AppBar(

          title: new Text(

            (Translations.of(context).text('main_title')),

            style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.w500),

          ),

          //elevation: 1.0,

          backgroundColor: midMainGreen,


          actions: <Widget>[

……..

……..

……..

Didier Boelens

unread,
May 17, 2018, 2:14:52 PM5/17/18
to Flutter Dev
Hi Niyazi,

As far as I can understand without the line numbers, the error is due to a "synchronization" issue.

In your initState(), you load your translations then, apply the localeChange.  However, you are not waiting for a completion.

At your build(BuildContext context) time, the latter does not wait and therefore, does not yet know anything about the translations (since not yet loaded).

My advice, in this very particular case would be to maybe:

1) create a async method, called by the initState()
2) this method would await for completion of the load and once completed, would set an internal variable (something like bool _isReady to true;) and call a setState((){});
3) at the build(BuildContext context), put String myString = "";  if (_isReady) { myString = Translations.of(context).text("main_title");}  and replace "appBar: new AppBar(title: new Text(myString, style:...),);

Hope this will help.



On Thursday, May 17, 2018 at 2:07:35 PM UTC+2, Niyazi Toros wrote:

Niyazi Toros

unread,
May 17, 2018, 2:45:02 PM5/17/18
to Flutter Dev
I will try this tomorrow.

Niyazi Toros

unread,
May 18, 2018, 1:47:27 AM5/18/18
to Flutter Dev
Thanks, I am getting a new error. I am posting whole main.dart. The rest of the code is same as you describe above.

After the main.dart I will add the error as well.

main.dart

import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'dart:async';

// Language
import 'package:flutter_localizations/flutter_localizations.dart';
import 'translations.dart';
import 'application.dart';
bool isReady;
SpecificLocalizationDelegate _localeOverrideDelegate;

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

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

class _MyAppState extends State<MyApp> {
SpecificLocalizationDelegate _localeOverrideDelegate;

@override
void initState(){
super.initState();
isReady = false;
_localeOverrideDelegate = new SpecificLocalizationDelegate(null);
setMyAppLanguage();
}

Future<bool> setMyAppLanguage() async {
applic.onLocaleChanged = await onLocaleChange;
setState(() {
isReady = true;

});
}

onLocaleChange(Locale locale){
setState((){
_localeOverrideDelegate = new SpecificLocalizationDelegate(locale);
});

}

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
if (isReady != true){

return new Center(
child: new CircularProgressIndicator(
backgroundColor: Colors.green.shade700,
)
);
} else {
String myTitleString = Translations.of(context).text('main_title');
return new MaterialApp(
title: 'My Application',
theme: new ThemeData(
primarySwatch: Colors.blue,
),

localizationsDelegates: [
_localeOverrideDelegate,
const TranslationsDelegate(),
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
],
supportedLocales: applic.supportedLocales(),
home: new Scaffold(
appBar: new AppBar(
title: new Text(myTitleString),
),
body: new Container(
),
),
);
}
}
}

And this is the error:


Launching lib/main.dart on Android SDK built for x86 in debug mode...

Initializing gradle...

Resolving dependencies...

Running 'gradlew assembleDebug'...

Built build/app/outputs/apk/debug/app-debug.apk (30.7MB).

Installing build/app/outputs/apk/app.apk...

I/FlutterActivityDelegate( 1394): onResume setting current activity to this

I/flutter ( 1394): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════

I/flutter ( 1394): The following NoSuchMethodError was thrown building MyApp(dirty, state: _MyAppState#eeaa2):

I/flutter ( 1394): The method 'text' was called on null.

I/flutter ( 1394): Receiver: null

I/flutter ( 1394): Tried calling: text("main_title")

I/flutter ( 1394): 

I/flutter ( 1394): When the exception was thrown, this was the stack:

I/flutter ( 1394): #0 Object.noSuchMethod (dart:core/runtime/libobject_patch.dart:46:5)

I/flutter ( 1394): #1 _MyAppState.build (file:///Users/niyazitoros/IdeaProjects/capital_locale/lib/main.dart:60:52)

I/flutter ( 1394): #2 StatefulElement.build (package:flutter/src/widgets/framework.dart:3722:27)

I/flutter ( 1394): #3 ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:3634:15)

I/flutter ( 1394): #4 Element.rebuild (package:flutter/src/widgets/framework.dart:3487:5)

I/flutter ( 1394): #5 BuildOwner.buildScope (package:flutter/src/widgets/framework.dart:2234:33)

I/flutter ( 1394): #6 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&RendererBinding&WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:626:20)

I/flutter ( 1394): #7 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding&PaintingBinding&RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:208:5)

I/flutter ( 1394): #8 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:990:15)

I/flutter ( 1394): #9 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:930:9)

I/flutter ( 1394): #10 _WidgetsFlutterBinding&BindingBase&GestureBinding&ServicesBinding&SchedulerBinding.scheduleWarmUpFrame.<anonymous closure> (package:flutter/src/scheduler/binding.dart:751:7)

I/flutter ( 1394): #12 _Timer._runTimers (dart:isolate/runtime/libtimer_impl.dart:382:19)

I/flutter ( 1394): #13 _Timer._handleMessage (dart:isolate/runtime/libtimer_impl.dart:416:5)

I/flutter ( 1394): #14 _RawReceivePortImpl._handleMessage (dart:isolate/runtime/libisolate_patch.dart:165:12)

I/flutter ( 1394): (elided one frame from package dart:async)

I/flutter ( 1394): ════════════════════════════════════════════════════════════════════════════════════════════════════

D/ ( 1394): HostConnection::get() New Host Connection established 0x9d119640, tid 1461

D/EGL_emulation( 1394): eglMakeCurrent: 0x9b636bc0: ver 3 0 (tinfo 0x9d103330)
Reply all
Reply to author
Forward
0 new messages