How to localize BottomNavigationBarItem?

52 views Asked by At

Could you please help me to undrestand how to properly localize the BottomNavigationBar? Here it is:

    class MainPage extends StatefulWidget {
      const MainPage({Key? key}) : super(key: key);
    
      @override
      State<MainPage> createState() => _MainPageState();
    }
    
    class _MainPageState extends State<MainPage> {
    
      int currentIndex = 0;
    
      final screens = [
        const Tab1(),
        const TabN(),
      ];
    
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
    
            localizationsDelegates: [
              AppLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalWidgetsLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],
            supportedLocales: [
              Locale('en', ''),
              Locale('it', ''),
              Locale('es', ''),
            ],
    
            home: Scaffold(
    
                appBar: AppBar(title: Builder(builder: (BuildContext context) {
                   return Align(
                       alignment: Alignment.topLeft,
                       child: Text(AppLocalizations.of(context)!.myTitle)); // I managed to handle it here!
                })),
    
                body: IndexedStack(
                  index: currentIndex,
                  children: screens,
                ),
    
                bottomNavigationBar: BottomNavigationBar(
                  
                  items: [
                    BottomNavigationBarItem(
                      label: 'Home', // OK but hardcoded
                      //label: AppLocalizations.of(context)!.tab1, // Error!
                    ),
                    
                    BottomNavigationBarItem(
                      label: 'TabN', // OK but hardcoded
                      //label: AppLocalizations.of(context)!.tabN // Error!
                    )
                  ],
                )));
      }
    }

The error says it is null. Looks like in label the context is lost or is not applied.

In case of appBar everything is right. The builder does the job. In case of label of BottomNavigationBarItem I didn't manage yet to do it.

How to manage this localization correct?

1

There are 1 answers

0
llaabbss On

Here is the solution: need to add builder.

return MaterialApp(

    localizationsDelegates: [
      AppLocalizations.delegate,
      GlobalMaterialLocalizations.delegate,
      GlobalWidgetsLocalizations.delegate,
      GlobalCupertinoLocalizations.delegate,
    ],
    supportedLocales: [
      Locale('en', ''),
      Locale('it', ''),
      Locale('es', ''),
    ],

    builder: (context, widget) => Scaffold(
        // The rest of the code
        // AppLocalizations.of(context)!.smth is now properly handled
    )
)