问题
When I try to localize a string in a TabBarView I get this error:
NoSuchMethodError: The method 'translate' was called on null. Receiver: null. Tried calling: translate("username).
I use this line of code to translate a key to a localized string:
AppLocalizations.of(context).translate('username')
This works great in all the other screens of my app except this one. Does anyone know why it's not working and how to solve it?
Some things I already tried:
pass the context of the main screen (the screen that holds all the TabBarViews)
wrap every ListTile in a Builder
wrap the ListView in a Builder
Code:
class AccountScreen extends StatelessWidget {
final String username;
final String email;
final int points;
AccountScreen(this.username, this.email, this.points);
@override
Widget build(BuildContext context) {
return Container(
child: Padding(
padding: EdgeInsets.all(10),
child: ListView(
children: <Widget>[
ListTile(
title: Text(AppLocalizations.of(context).translate('username')),
subtitle: Text(username),
),
ListTile(
title:
Text(AppLocalizations.of(context).translate('email_address')),
subtitle: Text(email),
),
ListTile(
title: Text(AppLocalizations.of(context).translate('points')),
subtitle: Text('$points'),
),
],
),
),
);
}
}
回答1:
I found same problem. But in my case is using MaterialApp
without localizationsDelegates
. (I mean all file not only main.dart
).
So i add localizationsDelegates
on every MaterialApp
in all widget.
e.g.
MaterialApp(
localizationsDelegates: [
MainLocalizationsDelegate.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
home: DefaultTabController(
length: 2,
child: Scaffold(
appBar: AppBar(
brightness: Brightness.light,
bottom: TabBar(
tabs: [
Tab(text: MainLocalizations.of(context).food),
Tab(text: MainLocalizations.of(context).car),
],
),
),
body: TabBarView(
children: [
TabA(),
TabB(),
],
),
),
),
);
回答2:
The problem was that there were multiple MaterialApp widgets inside the app that were causing some conflicts regarding the localisation process. Removing the Redundant MaterialApp widgets fixed the issue.
来源:https://stackoverflow.com/questions/57101411/cannot-localize-strings-in-flutter-tabbarview