Flutter Localization function not working after moving widget to another file?
Asked Answered
P

1

5

At first I implemented l10n from this tutorial to the template project file for Flutter and it was a success. After that, I tried to move the MyHomePage classes to a new file called home.dart. And it stopped working because when I call Translations.of(context) it returns null. Any difference of the BuildContext when inside main.dart and home.dart?

localization.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;

}

main.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", ""),
      ],
    );
  }
}

home.dart

import 'package:flutter/material.dart';

import 'package:kpop_idol/components/localization.dart';


class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Text(
              Translations.of(context).get('app_name'),
            ),
          ],
        ),
      ),
    );
  }
}
Pt answered 31/8, 2018 at 14:41 Comment(0)
T
9

Don't use relative imports in the file lib/main.dart

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

should be

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

You can upvote and follow https://github.com/dart-lang/sdk/issues/33076

Timbal answered 31/8, 2018 at 14:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.