Languages and RTL
Twelve layouts are built in, right to left included, and adding a thirteenth takes a map.
Install#
flutter pub add virtual_keypadimport 'package:virtual_keypad/virtual_keypad.dart';Registering the built-in layouts#
void main() {
initializeKeyboardLayouts(); // registers all 12 languages
runApp(const MyApp());
}Call it once at startup. Without it the keyboard falls back to English, which is the most common reason a language switch appears to do nothing.
Switching#
KeyboardLayoutProvider.instance.setLanguage('ar'); // Arabic, right to left
KeyboardLayoutProvider.instance.setLanguage('ko'); // Korean
KeyboardLayoutProvider.instance.setLanguage('en'); // EnglishLetting the user choose#
VirtualKeypad(
availableLanguages: ['en', 'bn', 'ar'],
initialLanguage: 'en',
onLanguageChanged: (code) {
prefs.setString('keyboardLanguage', code);
},
)With more than one entry, a long press on the space bar opens the picker. The first entry is that keyboard's fallback.
The selection lasts for the app session and is not persisted for you. Save the code from onLanguageChanged and pass it back as initialLanguage to restore it after a restart.
Right to left#
Arabic and other right to left layouts lay their keys out in the correct direction, and text goes into the field the way the field already handles direction. That means an RTL layout works inside an LTR app without wrapping anything in a Directionality widget.
Adding your own#
A layout is rows of keys, the same structure a custom layout uses, registered under a language code.
KeyboardLayoutProvider.instance.registerLanguage(
const KeyboardLanguage(
code: 'sv',
name: 'Swedish',
nativeName: 'Svenska',
textLayouts: KeyboardLayoutSet(
primary: [
[
VirtualKey.character(text: 'q'),
VirtualKey.character(text: 'w'),
// ... the rest of the row
],
],
secondary: numberSymbolRows, // the numbers page
),
),
);Only textLayouts is required. Leave emailLayouts, urlLayouts, numberLayouts and the rest off and the language falls back for those field types. Set isRTL: true for a right to left script.
Register before the keyboard is built, then include the code in availableLanguages. A contribution back to the package is welcome if the layout is a standard one for that language.
Shifted characters#
capsText is what a key inserts while shift or caps lock is on.
VirtualKey.character(text: 'a', capsText: 'A')Without it a shifted key falls back to the uppercase form of its text, which is right for Latin scripts and wrong for any script where shift reaches a different character rather than a taller one.