The application needs to implement language switching at runtime. Wrote a bloc with event and state and called BlocBuilder in main.dart. But I don't know how to implement the switch. How can I do that? In total, the application has two languages. My bloc:
class LanguageBloc extends Bloc<LanguageEvent, LanguageState> {
LanguageBloc() : super(InitialLang()) {
on<ChangeLang>(
(event, emit) {
emit(NewLang());
},
);
}
@immutable
abstract class LanguageEvent {}
class ChangeLang extends LanguageEvent {}
@immutable
abstract class LanguageState {}
class InitialLang extends LanguageState {}
class NewLang extends LanguageState {}
My main.dart
Widget build(BuildContext context) {
return MultiBlocProvider(
providers: [
BlocProvider(
create: (context) => BottomNavyBloc(),
),
BlocProvider(
create: (context) => LanguageBloc(),
),
],
child: BlocBuilder<LanguageBloc, LanguageState>(
builder: (context, state) {
return MaterialApp(
title: 'Flutter Demo',
localizationsDelegates: const [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
theme: ThemeData(
primarySwatch: Colors.blue,
),
debugShowCheckedModeBanner: false,
home: const HomeScreen(),
);
},
),
);
}
My lang btn:
ElevatedButton(onPressed: (){}, child: Text('Switch lang'))
What you can do is to send a variable Locale with the language of your choice, and in your MaterialApp in the locale attribute, you attach it.
Without complications you can use Cubit instead of Bloc, because it is not necessary to have events, then you could do the following:
Now in your main, as you have it, it would only look like this:
----- EDIT WITH BUTTON -----
I thought you would need a Switch Button that handles the booleans but no, you only need one button that will be the one to change it so I did it this way:
We will make our widget a StatefulWidget so we can just change the boolean variable and know if it is in English or French. If you don't want to use Stateful let me know, because we can use it with the same Cubit, but it would change the code and a little bit the logic of the LanguageCubit.