没有BuildContext的BottomNavigationBarItem的本地化?

时间:2020-07-17 10:53:11

标签: flutter localization

BottomNavigationBar标题需要本地化,但是没有上下文。当我尝试致电

 var v1 = BottomNavigationBarItem(icon: Icon(MyFlutterApp.kievstar_icon,size: 26.0), backgroundColor: Color(0xff20ade3), title: Text(AppLocalizations.of(context).translate('first_string')));

我得到了错误。该怎么办?我听不懂上下文,在flutter中非常复杂的本地化。

我的完整代码:

class Home extends StatefulWidget{

 @override
 _HomeState createState() => _HomeState();
 }


 class _HomeState extends State<Home>{

 int _selectedPage = 0;

 final _pageOptions = [Kievstar(), Vodafone(), Lifecell(), Para()];

 var v1 = BottomNavigationBarItem(icon: Icon(MyFlutterApp.kievstar_icon,size: 26.0), backgroundColor: Color(0xff20ade3), title: Text("Kievstar"));


 var v2 = BottomNavigationBarItem(icon: Icon(MyFlutterApp.vodafon_icon,size:    26.0), backgroundColor:Colors.red, title: Text('Vodafone'));

 var v3 = BottomNavigationBarItem(icon: Icon(MyFlutterApp.life_icon,size: 26.0), backgroundColor:Color(0xffffca07), title: Text('Lifecell'));

 var v4 = BottomNavigationBarItem(icon: Icon(MyFlutterApp.para_icon, size:   26.0), backgroundColor:Colors.deepPurple, title: Text('Couple'));



@override
Widget build(BuildContext context) {
 return Scaffold(
     body: _pageOptions[_selectedPage],
     bottomNavigationBar: BottomNavigationBar(
       currentIndex: _selectedPage,
       onTap: (int index) {
         setState(() {
           _selectedPage = index;
         });
       },
       elevation: 2,
       items: <BottomNavigationBarItem>[v1,v2,v3,v4],
       unselectedItemColor: Colors.white70,
       showUnselectedLabels: true,
      ));
   }

  }

1 个答案:

答案 0 :(得分:1)

BuildContext仅在build时才知道,而不是在实例化窗口小部件时:

@override
Widget build(BuildContext context) {
 // here you have the context
 // here you can build your items
 // or you can also use functions to build multi-use widgets and pass the context

 final _pageOptions = [Kievstar(), Vodafone(), Lifecell(), Para()];

 final v1 = BottomNavigationBarItem(
   icon: Icon(MyFlutterApp.kievstar_icon,size: 26.0), 
   backgroundColor: Color(0xff20ade3), 
   title: Text(YourLocalization.of(context).kievstar)
 );

 // v2,v3,...

 return Scaffold(
     body: _pageOptions[_selectedPage],
     bottomNavigationBar: BottomNavigationBar(
       currentIndex: _selectedPage,
       onTap: (int index) {
         setState(() {
           _selectedPage = index;
         });
       },
       elevation: 2,
       items: <BottomNavigationBarItem>[v1, /*...*/ ],
       unselectedItemColor: Colors.white70,
       showUnselectedLabels: true,
      ));
   }
}