Background
- I’m using
flutter_localizations
to localize my app. - I’m using
build_runner
for generating files. (riverpod
,freezed
etc).
pubspec.yaml
...
dependencies:
flutter:
sdk: flutter
flutter_localizations:
sdk: flutter
intl: 0.18.1
...
dev_dependencies:
build_runner: ^2.4.8
flutter_gen: ^5.4.0
...
flutter:
generate: true
...
l10n.yaml
arb-dir: lib/l10n
template-arb-file: app_en.arb
output-localization-file: app_localizations.dart
some_widget.dart
import 'package:flutter/material.dart';
import 'package:flutter_gen/gen_l10n/app_localizations.dart';
class SomeWidget extends StatelessWidget {
const SomeWidget({super.key});
@override
Widget build(BuildContext context) {
return Text(AppLocalizations.of(context).someText);
}
}
Problem
flutter_gen
is the issue. I must add package: flutter_gen to the dev dependency.
-
Why I must add this
After implementing localization according to the official Flutter Doc, running the command
dart run build_runner build
causes an error (Bad state: Unable to generate package graph
). This is discussed here. It was solved by addingflutter_gen
. -
Adding
flutter_gen
causes issuesFiles containing l10n code such as:
AppLocalizations.of(context).someText
raises an error:Target of URI doesn't exist: 'package:flutter_gen/gen_l10n/app_localizations.dart'
on import line'package:flutter_gen/gen_l10n/app_localizations.dart';
. This is explained here. Simplified, flutter creates the l10n generated files under a fake package name underflutter_gen
which conflicts with the realflutter_gen
added under dev dependency.
What I tried
-
Restarting VS Code, restarting Dart analyzer.
-
flutter clean, other various deleting cache methods.
I’m looking for a solution where I can import AppLocalizations
without errors and I can run build_runner
commands without error.
2
Answers
Since generating under a fake package name
flutter_gen
causes the issue, it can be prevented by changing the generated file output location to your source code (under the lib/ folder).Change:
l10n.yaml
some_widget.dart
Try running this command if the above answer doesn’t work for you.