Flutter设置标题时的本地化错误

huangapple go评论64阅读模式
英文:

flutter localization error when set title

问题

It seems like you're facing an issue with your Flutter code, specifically with the Localized.of(context).title line in your main.dart file. The error message you mentioned, "NoSuchMethodError: The getter 'title' was called on null," suggests that the Localized.of(context) call is returning null.

Here are a few things you can check:

  1. Ensure that you have properly initialized and set up your localization in your Flutter app.

  2. Make sure that the Localized class is correctly providing the localized titles based on the selected locale.

  3. Verify that your supportedLocales in MaterialApp match the locales you have defined in your Localized class (in this case, 'en' and 'ja').

  4. Check if you have added the necessary localization files and configuration for 'en' and 'ja' in your Flutter project.

  5. Ensure that you have imported the required packages correctly, especially the flutter_localizations package.

If you've double-checked these aspects and still encounter the error, it might be beneficial to provide more code context or share any additional error messages to help identify the specific issue in your code.

英文:

localizaed.dart

import 'package:flutter/cupertino.dart';

class Localized {
  Localized(this.locale);

  final Locale locale;

  static Localized of(BuildContext context) => Localizations.of<Localized>(context, Localized);
  static Map<String, Map<String,String>> _v = {
    'en': {
      'title': 'hello world',
    },
    'ja': {
      'title': 'こんちは'
    }
  };
  String get title => _v[locale.languageCode]['title'];
}

class LocalizedDelagate extends LocalizationsDelegate<Localized> {
  const LocalizedDelagate();

  @override
  bool isSupported(Locale locale) => ['en','ja'].contains(locale.languageCode);
  @override
  Future<Localized> load(Locale locale) async => Localized(locale);
  @override
  bool shouldReload(LocalizationsDelegate old) => false;
}

main.dart

import 'package:calculator/src/localization/localized.dart';
import 'package:flutter/material.dart';
import 'package:calculator/src/pages/HomePage.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

void main() => runApp(StockCalcApp());

class StockCalcApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        const LocalizedDelagate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        const Locale('en'),
        const Locale('ja'),
      ],
      onGenerateTitle: (BuildContext context) => Localized.of(context).title, // notthing problem
      theme: ThemeData(primarySwatch: Colors.pink),
      home: Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          title: Text(Localized.of(context).title), // and same code but, error. when I comment this line then, nothing well.
          backgroundColor: Colors.pink[900],
          elevation: 0.0,
        ),
        body: StockHome(),
      ),
    );
  }
}

I cannot understand why to occur an error this message on the screen.

NoSuchMethodError: The getter 'title' was called on null.

I just do this example find on the web. and I think.. is very simple .. I think.
but seriously I cannot understand why to bring up this message on the android emulator.

答案1

得分: 2

当您调用 onGenerateTitle: (BuildContext context) => Localized.of(context).title 时,它使用了一个新的 BuildContext,该上下文已经包含了 LocalizedDelagate(),因此可以使用 Localized.of(context) 来调用。

但是,当您在同一个 build 方法内使用它时,您引用了一个在 LocalizedDelagate() 创建之前的 context 实例,因此 Localized.of(context) 不会返回任何内容。

您可以通过创建一个新的小部件来避免这个问题,在其 build 方法中将具有更新的 BuildContext,从而可以访问 Localized。例如,创建一个名为 HomeScreen 的新小部件:

class StockCalcApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        const LocalizedDelagate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        const Locale('en'),
        const Locale('ja'),
      ],
      onGenerateTitle: (BuildContext context) => Localized.of(context).title, 
      theme: ThemeData(primarySwatch: Colors.pink),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          title: Text(Localized.of(context).title), // 这个上下文将能够访问 Localized
          backgroundColor: Colors.pink[900],
          elevation: 0.0,
        ),
        body: StockHome(),
    );
  }
}

这样,在 HomeScreen 中使用的上下文将能够访问 Localized

英文:

When you call onGenerateTitle: (BuildContext context) => Localized.of(context).title, it uses a new BuildContext, which already contains the LocalizedDelagate(), so it can be called with Localized.of(context).

When you use it within the same build method, you refer to an instance of context before the LocalizedDelagate() was created, so Localized.of(context) doesn't return anything.

You can avoid this problem by creating a new Widget, which will have an updated BuildContext in it's build method, that will have access to Localized.
For example, create a new widget named HomeScreen

class StockCalcApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      localizationsDelegates: [
        const LocalizedDelagate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        const Locale('en'),
        const Locale('ja'),
      ],
      onGenerateTitle: (BuildContext context) => Localized.of(context).title, 
      theme: ThemeData(primarySwatch: Colors.pink),
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        resizeToAvoidBottomPadding: false,
        appBar: AppBar(
          title: Text(Localized.of(context).title), // this context will have access to Localized
          backgroundColor: Colors.pink[900],
          elevation: 0.0,
        ),
        body: StockHome(),
    );
  }
}

huangapple
  • 本文由 发表于 2020年1月7日 00:12:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/59615382.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定