Closed easydo247 closed 3 years ago
Hi @easydo247,
Thanks for reporting this!
You are right, S.load(locale)
just loads messages for the passed locale, and does not set text direction.
Does a bit different approach work for you?
import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';
import 'generated/l10n.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
State<StatefulWidget> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
var _selectedLocale = S.delegate.supportedLocales[0];
void _handleLocaleChange(Locale locale) {
setState(() {
_selectedLocale = locale;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
localizationsDelegates: [
S.delegate,
GlobalMaterialLocalizations.delegate,
GlobalWidgetsLocalizations.delegate,
GlobalCupertinoLocalizations.delegate,
],
supportedLocales: S.delegate.supportedLocales,
locale: _selectedLocale,
home: MyHomePage(
onLocaleChange: _handleLocaleChange,
),
);
}
}
class MyHomePage extends StatelessWidget {
final Function(Locale) onLocaleChange;
MyHomePage({Key key, this.onLocaleChange}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(S.of(context).pageHomeTitle),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Row(
children: [
Text(S.of(context).pageHomeWelcome),
],
),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
OutlineButton(
child: Text('en'),
onPressed: () => onLocaleChange(
Locale.fromSubtags(languageCode: 'en'),
),
),
OutlineButton(
child: Text('ar_EG'),
onPressed: () => onLocaleChange(
Locale.fromSubtags(languageCode: 'ar', countryCode: 'EG'),
),
),
],
),
],
),
),
);
}
}
@lzoran You are amazing, thank you!
Global directionality change can be achieved with SetState, ChangeNotifier, ValueNotifier, BlocListener, etc...
But the killer idea is that we need to rebuild the MaterialApp to apply this, so simple! Many thanks.
The only thing missing here is rebuilding constant widgets, as they are not rebuilt.
There are two separate ways to overcome this:
S.current.myString
. This way when inherited widget triggers an update, even constant widgets are updated. Reference here. For this solution, I am experimenting with using S.of(context).myString
instead of S.current.myString
.I can confirm that B. worked for me, it's way easier. Just wrap the app under runApp
with RestartWidget
When I change the Locale to an RTL ( S.load(Locale('ar', 'EG')) ) writing, the app doesn't enter that mode.