Reputation: 5042
I try to change language after press button. I succes to change after app reboot, but I don't success to reload page after press button. I have this error.
Can't find the `I18n` widget up in the tree. Please make sure to wrap some ancestor widget with `I18n`.
here is my code
class menu7 extends StatefulWidget {
@override
_menu7State createState() => _menu7State();
}
class _menu7State extends State<menu7> {
save_data() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString("language","fr");
});
}
save_data2() async{
SharedPreferences prefs = await SharedPreferences.getInstance();
setState(() {
prefs.setString("language","en");
});
}
@override
void initState() {
super.initState();
}
@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.white,
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
MaterialButton(
color: Colors.blue,
child: Text("Francais",
style: const TextStyle(color: Colors.white, fontSize: 17),
),
onPressed: (){
save_data();
I18n.of(context).locale = Locale("fr");
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => DrawerPage(
),
));
}
),
MaterialButton(
color: Colors.blue,
child: Text("English",
style: const TextStyle(color: Colors.white, fontSize: 17),
),
onPressed: (){
setState(() {
save_data2();
I18n.of(context).locale = Locale("en");
Navigator.of(context).pushReplacement(
MaterialPageRoute(
builder: (context) => DrawerPage(
),
));
});
}
),
],
),
);
}
}
Upvotes: 1
Views: 247
Reputation: 1610
@Nitneuq The problem is because the I18n widget is not there in the widget tree in which your page is. you should move your I18n widget at the top of the widget tree as suggested here:
https://github.com/marcglasberg/i18n_extension/issues/10#issuecomment-594716633
like this runApp(I18n(child: MaterialApp()));
or you can move it somewhere central so that all your routes can access the Widget.
Upvotes: 3