How to make a dropdown localizer in my flutter app?

Viewed 2437

In my app there will be 2 languages (Arabic and English) I built a settings page where the user can switch language depending on the FlatButton they press. But I want to change the FlatButtons to DropdownButtons. At the moment the code works and I can successfully switch language in the app.

Here is how the code looks like:

import 'package:flutter/material.dart';

import '../drawer/drawer.dart';
import '../app_localization.dart';
import '../locale_helper.dart';

class AppSettings extends StatefulWidget {
  static const routeName = '/settings-screen';

  @override
  _AppSettingsState createState() => _AppSettingsState();
}

class _AppSettingsState extends State<AppSettings> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Settings',),
      ),
      drawer: MyDrawer(),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new FlatButton(
              child: new Text("English"),
              color: AppLocalizations.of(context).locale == "en"
                  ? Colors.grey
                  : Colors.blue,
              onPressed: () {
                this.setState(() {
                  helper.onLocaleChanged(new Locale("en"));
                });
              },
            ),
            new FlatButton(
              child: new Text("العربية"),
              color: AppLocalizations.of(context).locale == "ar"
                  ? Colors.grey
                  : Colors.blue,
              onPressed: () {
                this.setState(() {
                  helper.onLocaleChanged(new Locale("ar"));
                });
              },
            ),
          ],
        ),
      ),
    );
  }
}

1 Answers

Replace your two FlatButton with one DropdownButton like this:

DropdownButton(
  icon: Icon(Icons.language),
  items: [
    DropdownMenuItem( value: Locale( 'en' ),
      child: Text( 'English'),),
    DropdownMenuItem( value: Locale( 'ar' ),
      child: Text( 'العربية' ),
    ],
  onChanged: (v) => setState(() { helper.onLocaleChanged( v )}),
  value: AppLocalizations.of(context).locale,
),

As an alternative you can use InputLanguage from package flutter_input or just have a look how it is done there.

Related