将窗口小部件移动到另一个文件后,Flutter本地化功能不起作用?

时间:2018-08-31 14:41:21

标签: localization flutter

起初,我从this tutorial到Flutter的模板项目文件中实现了l10n,并获得了成功。 之后,我尝试将val bitmap = intent.extras.getParcelable<Bitmap>("image") 类移动到名为MyHomePage的新文件中。它停止工作,因为当我打电话给home.dart时,它返回了Translations.of(context)nullBuildContext内的main.dart有什么区别?

localization.dart

home.dart

main.dart

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

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

class Translations {
  final Locale locale;
  Map<String, dynamic> _messages;

  Translations(this.locale);

  static Translations of(BuildContext context) => Localizations.of<Translations>(context, Translations);

  Future<bool> load() async {
    String fileName = 'lang/${locale.languageCode}.json';
    String data = await rootBundle.loadString(fileName);

    _messages = json.decode(data);
    return true;
  }

  String get(String key) => _messages[key] ?? "** $key not found";
}

class TranslationsDelegate extends LocalizationsDelegate<Translations> {
  @override
  bool isSupported(Locale locale) => ['en', 'id'].contains(locale.languageCode);

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

    return translations;
  }

  @override
  bool shouldReload(LocalizationsDelegate<Translations> old) => false;

}

home.dart

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

import 'components/localization.dart';
import 'components/theme.dart';
import 'views/home.dart';

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      onGenerateTitle: (BuildContext context) {
        print(context);
        return Translations.of(context).get('app_name');
      },
      theme: appTheme,
      home: MyHomePage(
        title: "Coba",
      ),
      debugShowCheckedModeBanner: false,
      localizationsDelegates: [
        TranslationsDelegate(),
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate
      ],
      supportedLocales: [
        Locale("en", ""),
        Locale("id", ""),
      ],
    );
  }
}

1 个答案:

答案 0 :(得分:3)

不要在文件lib/main.dart中使用相对导入

import 'components/localization.dart';
import 'components/theme.dart';
import 'views/home.dart';

应该是

import 'package:my_package/components/localization.dart';
import 'package:my_package/components/theme.dart';
import 'package:my_package/views/home.dart';

您可以投票并关注https://github.com/dart-lang/sdk/issues/33076