Flutter NoSuchMethodErro: The method 'tr' was called on null. Receiver: null
Asked Answered
F

4

1

I am new in flutter, i am trying to localize languages, but getting error

 localizationsDelegates: <LocalizationsDelegate>[
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,


        EasyLocalizationDelegate(
          locale: data.locale ?? Locale('en', 'US'),
          path: 'resources/langs',
        ),
      ],
      supportedLocales: <Locale>[
        const Locale("en", "US"),
        const Locale("ar", "AR"),
      ],

getting error The method 'tr' was called on null. Receiver: null Tried calling: tr("Click here to continue") in the line in basescreen file

Text(
            AppLocalizations.of(context).tr('Click here to continue'),
//              "Click here to continue",
style: _textStyle,
),

enter image description here

my load functin is

Future<bool> load() async {
// Load the language JSON file from the "lang" folder
developer.log('file name', name: 'lang/${locale.languageCode}.json');
String jsonString =
await rootBundle.loadString('lang/${locale.languageCode}.json');
//await rootBundle.loadString('lang/${locale.languageCode}-${locale.countryCode}.json');
developer.log('file text', name: jsonString);
Map<String, dynamic> jsonMap = json.decode(jsonString);

_localizedStrings = jsonMap.map((key, value) {
  return MapEntry(key, value.toString());
});

return true;

}

directory files are enter image description here

i have also added the blow code in my pubspec.yaml asset

    - lang/
- resources/langs/en-US.json
- resources/langs/ar-AR.json
Fjeld answered 20/7, 2020 at 8:36 Comment(1)
Have you solved the problem?Bora
P
2

Did you follow the complete example on the flutter page? Maybe you just missing something!

This is my configuration and it works fine:

main.dart

localizationsDelegates: [
      AppLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalMaterialLocalizations.delegate,
    ],
    supportedLocales: [
      const Locale('en'),
      const Locale('it')
    ],

appLocalization.dart

import 'dart:convert';

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

class AppLocalizations{
  final Locale locale;

  AppLocalizations(this.locale);

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

  static const LocalizationsDelegate<AppLocalizations> delegate = _AppLocalizationsDelegate();

  Map<String,String> _localizedStrings;

  Future<bool> load() async{
    String jsonString = await rootBundle.loadString('i18n/${locale.languageCode}.json');
    Map<String,dynamic> jsonMap = json.decode(jsonString);

    _localizedStrings = jsonMap.map((key, value){
      return MapEntry(key,value.toString());
    });
    return true;
  }

  String translate(String key){
    return _localizedStrings[key];
  }

  
}

class _AppLocalizationsDelegate
    extends LocalizationsDelegate<AppLocalizations> {
  // This delegate instance will never change (it doesn't even have fields!)
  // It can provide a constant constructor.
  const _AppLocalizationsDelegate();

  @override
  bool isSupported(Locale locale) {
    // Include all of your supported language codes here
    return ['en', 'it'].contains(locale.languageCode);
  }

  @override
  Future<AppLocalizations> load(Locale locale) async {
    // AppLocalizations class is where the JSON loading actually runs
    AppLocalizations localizations = new AppLocalizations(locale);
    await localizations.load();
    return localizations;
  }

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

two files inside the i18n folder and this is in the pubspec.yaml

  assets:
- i18n/it.json
- i18n/en.json

and finally, just call it like

AppLocalizations.of(context).translate('companyName'),

Palimpsest answered 20/7, 2020 at 9:22 Comment(5)
yes i have done the all steps, but error still existFjeld
are you using any type of packages for this? that EasyLocalizationDelegate( locale: data.locale ?? Locale('en', 'US'), path: 'resources/langs', ), doesnt't seems rightPalimpsest
well, first of all, you should not mix two different ways together! my way use only the flutter implementation without the plugin to avoid useless boilerplate. Second i dont know this plugin but as i can see there is not load() method in the configuration section here: github.com/aissat/easy_localization, try only follow that (so using the runApp way) and the Translate tr() sectionPalimpsest
there is load() method available in the AppLocalizations class, actually the code is written by an other developer, i am trying to fix the error in that...Fjeld
yes but that method does not seems to be from the plugin you mentioned. That load method is used here flutter.dev/docs/development/accessibility-and-localization/…. So, do you really need that package?Palimpsest
L
2

For me, I found that I had added the MaterialApp widget, nested, further down the widget by accident. So, adding the second MaterialApp widget overrode what I had previously defined.

Loveinidleness answered 12/10, 2020 at 3:53 Comment(0)
P
1

This issue happened to me because the MaterialApp requires the child specified in home: to be an actual separate StatelessWidget rather than just directly nested.

If the widget is directly nested at home:, then an InheritedWidget cannot be added in between them, so there will not be a Localizations widget to access from the BuildContext.

Pumpernickel answered 30/11, 2020 at 4:29 Comment(0)
M
0

I had the same problem, I realize that the problem is in page that make call. The page that make call had a Widget that return MaterialApp, inside I had a button that call the page and got the error "The method 'tr' was called on null". I changed the page to:

Widget build(BuildContext context) {
    var data = EasyLocalizationProvider.of(context).data;
    return EasyLocalizationProvider(
      data: data,
      child: Scaffold(...

Inside Scaffold there is the button that call a page and there is no problem anymore.

Memorialist answered 21/1, 2021 at 19:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.