How to make a dropdown localizer in my flutter app?

2,011

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.

Share:
2,011
theduck
Author by

theduck

Updated on December 14, 2022

Comments

  • theduck
    theduck over 1 year

    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"));
                    });
                  },
                ),
              ],
            ),
          ),
        );
      }
    }
    
    
    • Michael Horn
      Michael Horn over 4 years
      Just to be clear - You want to convert your two FlatButtons to a single dropdown which contains all language options, is that correct?
    • Admin
      Admin over 4 years
      yes correct @MichaelHorn