right-to-left (RTL) in flutter

生来就可爱ヽ(ⅴ<●) 提交于 2019-11-30 11:49:00

first you must add flutter_localizations package to your pubspec.yml

dependencies:
  flutter:
    sdk: flutter
  flutter_localizations:
    sdk: flutter

now you have two choices :

1. force a locale ( and direction ) on all devices

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

MaterialApp(
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ],
  supportedLocales: [
    Locale("fa", "IR"), // OR Locale('ar', 'AE') OR Other RTL locales
  ],
  locale: Locale("fa", "IR") // OR Locale('ar', 'AE') OR Other RTL locales,
  .
  .
  .
);

2. set layout direction according to device locale ( if user phone locale is a RTL language and exist in supportedLocales, your app run in RTL mode, otherwise your app is LTR )

import 'package:flutter/material.dart';
import 'package:flutter_localizations/flutter_localizations.dart';

MaterialApp(
  localizationsDelegates: [
    GlobalMaterialLocalizations.delegate,
    GlobalWidgetsLocalizations.delegate,
  ],
  supportedLocales: [
    Locale("en", "US"),
    Locale("fa", "IR"), // OR Locale('ar', 'AE') OR Other RTL locales
  ],
  .
  .
  .
);

note : rtl languages in flutter is :

static const List<String> _rtlLanguages = <String>[
    'ar', // Arabic
    'fa', // Farsi
    'he', // Hebrew
    'ps', // Pashto
    'ur', // Urdu
  ];

You need to create a Builder and pass it the layout direction using TextDirection.rtl

new MaterialApp(
          title: 'Flutter RTL',
          color: Colors.grey,
          builder: (BuildContext context, Widget child) {
              return new Directionality(
                textDirection: TextDirection.rtl,
                child: new Builder(
                  builder: (BuildContext context) {
                    return new MediaQuery(
                      data: MediaQuery.of(context).copyWith(
                            textScaleFactor: 1.0,
                          ),
                      child: child,
                    );
                  },
                ),
              );
            },
          .
          .
          .
        );

Please check Internationalization Flutter app (Arabic RTL) https://proandroiddev.com/internationalization-flutter-app-arabic-rtl-fe99bfae696e

If you need Right to left or Left to right in text field. you can use TextDirection in TextField

TextField(
  textDirection: TextDirection.rtl,
  decoration: InputDecoration(
    labelText: "Enter Pashto Name",
  ),
),

The best and shortest way to set RTL configuration for the entire app.

void main() {
  runApp(
    MaterialApp(
      home: Directionality( // add this
        textDirection: TextDirection.rtl, // set this property 
        child: HomePage(),
      ),
    ),
  );
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!