Flutter: меню DropdownButton не открывается автоматически при фокусировке - PullRequest
1 голос
/ 17 апреля 2020

Я работаю над flutter веб-приложением. Я использую два виджета флаттера, один - TextField, а другой - DropdownButton. Когда я нажимаю на текстовое поле и смещаю фокус на раскрывающемся поле, нажимая клавишу вкладки на клавиатуре или завершая редактирование текстового поля, я могу получить фокус на DropdownButton, но раскрывающееся меню не открывается, чтобы выбрать значение с помощью клавиатуры .

Я хочу, чтобы это раскрывающееся меню открывалось автоматически, как только я сфокусировался на виджете DropdownButton, где я хочу изменить выбор с помощью клавиш со стрелками на клавиатуре.

Вот пример кода для вашей справки. Вы можете запустить код напрямую, вставив его в IDE.

import 'package:flutter/material.dart';


void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String _myActivity;
  String _myActivityResult;
  final formKey = new GlobalKey<FormState>();

  FocusNode _dropdown = new FocusNode();
  FocusNode _textField = new FocusNode();

  final _dropdownButtonKey = GlobalKey();

  TextEditingController textController;
  @override
  void initState() {
    super.initState();
    _myActivity = '';
    _myActivityResult = '';
    textController = TextEditingController.fromValue(TextEditingValue(text: textValue));
    _dropdown.addListener(focusChange);
  }

  focusChange() {
    if(_dropdown.hasFocus) {
      print('drop down has focus now');
    }
  }
  _saveForm() {
    var form = formKey.currentState;
    if (form.validate()) {
      form.save();
      setState(() {
        _myActivityResult = _myActivity;
      });
    }
  }
  var textValue = '';
  String dropdownValue = 'One';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Form'),
      ),
      body: Center(
        child: Form(
          key: formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: <Widget>[
              Focus(
                child: TextField(
                  focusNode: _textField,
                  style: TextStyle(fontSize: 12.0),
                  autocorrect: false,
                  onEditingComplete: (){
                    _textField.unfocus();
                    _dropdown.requestFocus();
                  },
                  controller: textController,
                  keyboardType: TextInputType.text,
                  onChanged: (String newVal) {
                    setState(() {
                      textValue = newVal;
                    });
                  },
                  textAlign: TextAlign.start,
                ),
              ),
              Container(
                padding: EdgeInsets.all(16),
                child: DropdownButton<String>(
                  value: dropdownValue,
                  focusNode: _dropdown ,
                  key: _dropdownButtonKey,
                  icon: Icon(Icons.arrow_downward),
                  iconSize: 24,
                  elevation: 16,
                  style: TextStyle(
                      color: Colors.deepPurple
                  ),
                  underline: Container(
                    height: 2,
                    color: Colors.deepPurpleAccent,
                  ),
                  onChanged: (String newValue) {
                    setState(() {
                      dropdownValue = newValue;
                    });
                    _dropdown.nextFocus();
                  },
                  items: <String>['One', 'Two', 'Three', 'Four']
                      .map<DropdownMenuItem<String>>((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  })
                      .toList(),
                )
              ),
              Container(
                padding: EdgeInsets.all(8),
                child: RaisedButton(
                  child: Text('Save'),
                  onPressed: _saveForm,
                ),
              ),
              Container(
                padding: EdgeInsets.all(16),
                child: Text(_myActivityResult),
              )
            ],
          ),
        ),
      ),
    );
  }
}
...