In the settings page of my app, I would like to add an option that controls the app language.
I can set the language before starting the app like this:
Wrap your MaterialApp
into a StreamBuilder
which will be responsible for providing the Locale
value to your application. And it will enable you to dynamically change it without restarting your app. This is an example using the rxdart package to implement the stream:
@override
Widget build(BuildContext context) {
return StreamBuilder(
stream: setLocale,
initialData: Locale('ar',''),
builder: (context, localeSnapshot) {
return MaterialApp(
// other arguments
locale: localeSnapshot.data,
);
}
);
}
Stream setLocale(int choice) {
var localeSubject = BehaviorSubject() ;
choice == 0 ? localeSubject.sink.add( Locale('ar','') ) : localeSubject.sink.add( Locale('en','') ) ;
return localeSubject.stream.distinct() ;
}
The above demonstration is just a basic way of how to achieve what you want to, but for a proper implementation of streams in your app you should consider using app-wide BloCs, which will significantly improve the quality of your app by reducing the number of unnecessary builds.