Flutter 如何根据在颤振中选择的下拉项添加文本字段值

Flutter 如何根据在颤振中选择的下拉项添加文本字段值,flutter,drop-down-menu,selection,textfield,flutter-layout,Flutter,Drop Down Menu,Selection,Textfield,Flutter Layout,在这里,当我从下拉列表中选择值时,国家/地区代码文本字段值将根据选择的下拉列表项进行更改,在本例中,当我从下拉列表中选择美国时,我有一些静态值。国家代码值自动更改为+1,当我从下拉列表中选择印度时,国家代码将更改为+91 这是输出的图像,因此您可以获得更好的想法 这是我试过的代码 import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter/serv

在这里,当我从下拉列表中选择值时,国家/地区代码文本字段值将根据选择的下拉列表项进行更改,在本例中,当我从下拉列表中选择美国时,我有一些静态值。国家代码值自动更改为+1,当我从下拉列表中选择印度时,国家代码将更改为+91

这是输出的图像,因此您可以获得更好的想法

这是我试过的代码

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

import 'package:flutter_masked_text/flutter_masked_text.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

import 'package:tudo/src/modules/signup/index.dart';

import 'package:tudo/src/utils/app_constants_value.dart';
import 'package:tudo/src/utils/roundrectbutton.dart';

class SignupScreen extends StatefulWidget {
  const SignupScreen({
    Key key,
    @required SignupBloc signupBloc,
  })  : _signupBloc = signupBloc,
        super(key: key);

  final SignupBloc _signupBloc;

  @override
  SignupScreenState createState() {
    return new SignupScreenState(_signupBloc);
  }
}

class SignupScreenState extends State<SignupScreen> {
  final SignupBloc _signupBloc;
  SignupScreenState(this._signupBloc);

  static final List<String> _dropdownItems = <String>['India', 'USA'];
  final formKey = new GlobalKey<FormState>();
  bool _validate = false;

  Person person = new Person();
  var controller = new MaskedTextController(mask: '(000) 000 0000');
  String _dropdownValue = 'India';
  String _countryCode = '+91';
  String _errorText;

  @override
  void initState() {
    super.initState();
    this._signupBloc.dispatch(LoadSignupEvent());
  }

  @override
  void dispose() {
    super.dispose();
  }

  Widget _buildCountry() {
    return FormField(
      builder: (FormFieldState state) {
        return DropdownButtonHideUnderline(
          child: new Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              new InputDecorator(
                decoration: InputDecoration(
                  filled: false,
                  hintText: 'Choose Country',
                  prefixIcon: Icon(Icons.location_on),
                  labelText:
                      _dropdownValue == null ? 'Where are you from' : 'From',
                  errorText: _errorText,
                ),
                isEmpty: _dropdownValue == null,
                child: new DropdownButton<String>(
                  value: _dropdownValue,
                  isDense: true,
                  onChanged: (String newValue) {
                    print('value change');
                    print(newValue);
                    person.country = newValue;
                    if (newValue == 'India') {
                      person.countryCode = '+91';
                    } else if (newValue == 'USA') {
                      person.countryCode = '+1';
                    } else {
                      person.countryCode = '+1';
                    }
                    setState(() {
                      _countryCode = person.countryCode;
                      _dropdownValue = person.country;
                    });
                    print('person.countryCode');
                    print('${person.countryCode}');
                  },
                  items: _dropdownItems.map((String value) {
                    return DropdownMenuItem<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                ),
              ),
            ],
          ),
        );
      },
    );
  }

  Widget _buildPhonefiled() {
    return Row(
      children: <Widget>[
        new Expanded(
          child: new TextFormField(
            initialValue: _countryCode,
            enabled: false,
            decoration: InputDecoration(
              filled: false,
              prefixIcon: Icon(FontAwesomeIcons.globe),
              labelText: AppConstantsValue.appConst['signup']['code']
                  ['translation'],
              hintText: "Country code",
            ),
            // onSaved: (String value) {
            //   setState(() {
            //     _countryCode = person.countryCode;
            //   });
            // },
          ),
          flex: 2,
        ),
        new SizedBox(
          width: 10.0,
        ),
        new Expanded(
          child: new TextFormField(
            controller: controller,
            keyboardType: TextInputType.number,
            decoration: InputDecoration(
              filled: false,
              labelText: AppConstantsValue.appConst['signup']['mobile']
                  ['translation'],
              hintText: "Mobile number",
              prefixIcon: new Icon(Icons.mobile_screen_share),
            ),
            onSaved: (String value) {
              person.phoneNumber = value;
            },
          ),
          flex: 5,
        ),
      ],
    );
  }

  Widget _buildSignupButton(BuildContext context) {
    return GestureDetector(
      child: RoundrectButton.buildRoundedRectButton(
          AppConstantsValue.appConst['signup']['signup']['translation'],
          signUpGradients,
          false),
      onTap: () {
        //  _submit();
        final FormState form = formKey.currentState;
        form.save();
        if (form.validate() && person.termsAndCondition) {
          Map<String, dynamic> signupdata = {
            'countyCode': person.countryCode,
            'phoneNumber': person.phoneNumber,
          };
        } else {
          setState(() {
            _validate = true;
          });
        }
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      top: false,
      bottom: false,
      child: Form(
        key: formKey,
        autovalidate: _validate,
        child: Scrollbar(
          child: SingleChildScrollView(
            dragStartBehavior: DragStartBehavior.down,
            padding: const EdgeInsets.symmetric(horizontal: 16.0),
            child: new Container(
              margin: EdgeInsets.fromLTRB(30, 100, 30, 0),
              child: new Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.center,
                children: [
                  _buildCountry(),
                  _buildPhonefiled(),
                  SizedBox(
                    height: 20.0,
                  ),
                  _buildSignupButton(context),

                ],
              ),
            ),
          ),
        ),
      ),
    );
  }
}

class Person {
  String email = '';
  String country = '';
  String countryCode = '';
  String phoneNumber = '';
  String firstname = '';
  String lastname = '';
  String password = '';
  bool termsAndCondition = false;
}
import'package:flatter/signatures.dart';
进口“包装:颤振/材料.省道”;
导入“包:flifter/services.dart”;
导入“package:flatter_masked_text/flatter_masked_text.dart”;
导入“package:font_awesome_flatter/font_awesome_flatter.dart”;
导入“package:tudo/src/modules/signup/index.dart”;
导入“package:tudo/src/utils/app_constants_value.dart”;
导入“package:tudo/src/utils/roundrectbutton.dart”;
类SignupScreen扩展StatefulWidget{
屏幕上的常量符号({
关键点,
@所需的SignupBloc SignupBloc,
}):_signupBloc=signupBloc,
超级(键:键);
最终签署方(SignupBloc)u SignupBloc ;;
@凌驾
SignupScreenState createState(){
返回新的SignupScreenState(_signupBloc);
}
}
类SignupScreenState扩展状态{
最终签署方(SignupBloc)u SignupBloc ;;
SignupScreenState(本.\u signupBloc);
静态最终列表_dropdownItems=[“印度”、“美国”];
final formKey=new GlobalKey();
bool _validate=false;
Person=新人();
var控制器=新的MaskedTextController(掩码:'(000)000 0000');
字符串_dropdownValue='India';
字符串_countryCode='+91';
字符串错误文本;
@凌驾
void initState(){
super.initState();
此._signuploc.dispatch(LoadSignupEvent());
}
@凌驾
无效处置(){
super.dispose();
}
Widget_buildCountry(){
返回表单字段(
生成器:(FormFieldState){
返回DropdownButtonHideUnderline(
子:新列(
crossAxisAlignment:crossAxisAlignment.stretch,
儿童:[
新输入装饰器(
装饰:输入装饰(
填充:假,
hintText:“选择国家”,
前缀图标:图标(图标位置打开),
标签文本:
_dropdownValue==null?“您来自哪里?”:“来自”,
errorText:\u errorText,
),
isEmpty:_dropdownValue==null,
孩子:新的下拉按钮(
值:_dropdownValue,
是的,
onChanged:(字符串newValue){
打印(“值更改”);
打印(新值);
person.country=newValue;
如果(新值==‘印度’){
person.countryCode='+91';
}否则如果(newValue=='USA'){
person.countryCode='+1';
}否则{
person.countryCode='+1';
}
设置状态(){
_countryCode=person.countryCode;
_dropdownValue=person.country;
});
打印('person.countryCode');
打印(“${person.countryCode}”);
},
items:_dropdownItems.map((字符串值){
返回下拉菜单项(
价值:价值,
子项:文本(值),
);
}).toList(),
),
),
],
),
);
},
);
}
Widget_buildphonefield(){
返回行(
儿童:[
新扩展(
子项:新建TextFormField(
initialValue:\u countryCode,
启用:false,
装饰:输入装饰(
填充:假,
前缀:图标(FontAwesomeIcons.globe),
labelText:AppConstantValue.appConst['signup']['code']
[“翻译”],
hintText:“国家代码”,
),
//onSaved:(字符串值){
//设置状态(){
//\u countryCode=person.countryCode;
//   });
// },
),
弹性:2,
),
新尺寸盒子(
宽度:10.0,
),
新扩展(
子项:新建TextFormField(
控制器:控制器,
键盘类型:TextInputType.number,
装饰:输入装饰(
填充:假,
labelText:AppConstantValue.appConst['signup']['mobile']
[“翻译”],
hintText:“手机号码”,
prefixIcon:新图标(图标、移动屏幕和共享),
),
onSaved:(字符串值){
person.phoneNumber=值;
},
),
弹性:5,
),
],
);
}
小部件构建签名按钮(构建上下文){
返回手势检测器(
子项:RoundrectButton.buildRoundedRectButton(
AppConstantsValue.appConst['signup']['signup']['translation'],
注册梯度,
假),,
onTap:(){
//_submit();
最终FormState表单=formKey.currentState;
form.save();
if(form.validate()&&person.termsAndCondition){
地图符号更新a={
“countyCode”:person.countryCode,
“phoneNumber”:person.phoneNumber,
};
}否则{
设置状态(){
_验证=真;
});
}
},
);
}
@凌驾
小部件构建(构建上下文){
返回安全区(
上图:错,
底部:错误,
孩子:表格(
key:formKey,
自动验证:_验证,
子:滚动条(
子:SingleChildScrollView(
import 'package:flutter/material.dart';
import 'package:flutter_masked_text/flutter_masked_text.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

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

class _MyHomePageState extends State<MyHomePage> {
//  static final List<String> _dropdownItems = <String>['India', 'USA'];
  static List<CountryModel> _dropdownItems = new List();
  final formKey = new GlobalKey<FormState>();

  var controller = new MaskedTextController(mask: '(000) 000 0000');
  CountryModel _dropdownValue;
  String _errorText;
  TextEditingController phoneController = new TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setState(() {
      _dropdownItems.add(CountryModel(country: 'India', countryCode: '+91'));
      _dropdownItems.add(CountryModel(country: 'USA', countryCode: '+1'));
      _dropdownValue = _dropdownItems[0];
      phoneController.text = _dropdownValue.countryCode;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
  appBar: AppBar(
    // Here we take the value from the MyHomePage object that was created by
    // the App.build method, and use it to set our appbar title.
    title: Text('Demo'),
  ),
  body: Center(
    // Center is a layout widget. It takes a single child and positions it
    // in the middle of the parent.
    child: Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        _buildCountry(),
        _buildPhonefiled(),
      ],
    ),
  ),
);
  }

  Widget _buildCountry() {
return FormField(
  builder: (FormFieldState state) {
    return DropdownButtonHideUnderline(
      child: new Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          new InputDecorator(
            decoration: InputDecoration(
              filled: false,
              hintText: 'Choose Country',
              prefixIcon: Icon(Icons.location_on),
              labelText:
                  _dropdownValue == null ? 'Where are you from' : 'From',
              errorText: _errorText,
            ),
            isEmpty: _dropdownValue == null,
            child: new DropdownButton<CountryModel>(
              value: _dropdownValue,
              isDense: true,
              onChanged: (CountryModel newValue) {
                print('value change');
                print(newValue);
                setState(() {
                  _dropdownValue = newValue;
                  phoneController.text = _dropdownValue.countryCode;
                });
              },
              items: _dropdownItems.map((CountryModel value) {
                return DropdownMenuItem<CountryModel>(
                  value: value,
                  child: Text(value.country),
                );
              }).toList(),
            ),
          ),
        ],
      ),
    );
  },
);
  }

  Widget _buildPhonefiled() {
return Row(
  children: <Widget>[
    new Expanded(
      child: new TextFormField(
        controller: phoneController,
        enabled: false,
        decoration: InputDecoration(
          filled: false,
          prefixIcon: Icon(FontAwesomeIcons.globe),
          labelText: 'code',
          hintText: "Country code",
        ),
      ),
      flex: 2,
    ),
    new SizedBox(
      width: 10.0,
    ),
    new Expanded(
      child: new TextFormField(
        controller: controller,
        keyboardType: TextInputType.number,
        decoration: InputDecoration(
          filled: false,
          labelText: 'mobile',
          hintText: "Mobile number",
          prefixIcon: new Icon(Icons.mobile_screen_share),
        ),
        onSaved: (String value) {},
      ),
      flex: 5,
    ),
  ],
);
  }
}

class CountryModel {
  String country = '';
  String countryCode = '';

  CountryModel({
    this.country,
    this.countryCode,
  });
}