Change the text direction depend on the language in flutter

Viewed 1164

I have a note app which allows the user to type notes I want if the language the user using is arabic to set the text direction to rtl otherwise set it to ltr in the text field and the details screen where I use listTile

How can I do that?

3 Answers

Try using langdetect (if you use tkinter)

from langdetect import detect
from tkinter import *
from tkinter.constants import *

arabictext = "مرحبا"

root = Tk()
text = Text(root)
lang = detect(arabictext)

if lang == "ar":
    text.tag_configure('tag-right', justify='right')
    text.insert('end', arabictext, 'tag-right')
    text.grid()

root.mainloop()

From official documentation

By default, Flutter only provides US English localizations. To add support for other languages, an application must specify additional MaterialApp (or CupertinoApp) properties, and include a package called flutter_localizations. As of November 2020, this package supports 78 languages.

To use flutter_localizations, add the package as a dependency to your pubspec.yaml file:

    dependencies:
  flutter:
    sdk: flutter
  flutter_localizations: # Add this line
    sdk: flutter         # Add this line

Next, run pub get packages, then import the flutter_localizations library and specify localizationsDelegates and supportedLocales for MaterialApp:

    import 'package:flutter_localizations/flutter_localizations.dart';
// TODO: uncomment the line below after codegen
// import 'package:flutter_gen/gen_l10n/app_localizations.dart';

// ...

MaterialApp(
 localizationsDelegates: [
   // ... app-specific localization delegate[s] here
   // TODO: uncomment the line below after codegen
   // AppLocalizations.delegate,
   GlobalMaterialLocalizations.delegate,
   GlobalWidgetsLocalizations.delegate,
   GlobalCupertinoLocalizations.delegate,
 ],
 supportedLocales: [
    const Locale('en', ''), // English, no country code
    const Locale('ar', ''), // Arabic, no country code
    const Locale.fromSubtags(languageCode: 'zh'), // Chinese *See Advanced Locales below*
    // ... other locales the app supports
  ],
  // ...
)

After introducing the flutter_localizations package and adding the code above, the Material and Cupertino packages should now be correctly localized in one of the 78 supported locales. Widgets should be adapted to the localized messages, along with correct left-to-right and right-to-left layout. Try switching the target platform’s locale to Arabic (ar) and notice that the messages should be localized and widgets are laid out with right-to-left layout in mind.

you can use this

https://pub.dev/packages/auto_direction

This package changes the direction of a widget from ltr direction into rtl direction and vice versa based on the language of the text provided.

Related