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

强颜欢笑 提交于 2021-02-11 14:10:46

问题


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,
),

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

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

    - lang/
- resources/langs/en-US.json
- resources/langs/ar-AR.json

回答1:


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'),




回答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.




回答3:


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.




回答4:


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.



来源:https://stackoverflow.com/questions/62991563/flutter-nosuchmethoderro-the-method-tr-was-called-on-null-receiver-null

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!