Flutter Dropdownbutton 状态未更新 - 其他一切正常

发布于 2025-01-18 01:45:36 字数 10440 浏览 2 评论 0原文

我创建了一个状态的客户信息表格,其中有两个使用状态的小部件 - 两个带有无线电按钮的列表图块和一个下拉按钮。列表图块响应代码并更新其状态,并根据预期将数据保存到变量中。

但是下拉按钮仅将值保存在分配的变量中,但不会显示新值而不是提示。

我遵循了示例代码,但是由于我是新手的扑朔迷离,所以找不到不幸的地方。谢谢您的任何帮助!

代码如下;请注意,某些标签文本使用我的母语,不会影响代码可读性。所讨论的代码以粗体(**)为单位。

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class CustomerForm extends StatefulWidget {
  const CustomerForm({Key key}) : super(key: key);
  @override
  CustomerFormState createState() {
    return CustomerFormState();
  }}


class CustomerFormState extends State<CustomerForm> {
  final formKey = GlobalKey<FormState>();

  String _name = '';
  String _age = '';
  String _nic = '';
  String _sex = '';
  String _telephone = '';
  String _address = '';
  String _email = '';
  String _inquiry = '';
**String _branch = '';**




  @override
    Widget build(BuildContext context) => Scaffold(
      resizeToAvoidBottomInset : false,
     appBar: AppBar(
      title: Text('ඔබේ තොරතුරු පහත පුරවන්න',
      style: TextStyle(
      fontSize: (20.0),),),
      centerTitle: true,
      backgroundColor: Colors.cyan,
      shadowColor: Colors.tealAccent[50] ),
      body:SingleChildScrollView(
        child: Form(
            key: formKey,
              child: Column(children:[
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      autofocus: true,
                      decoration: InputDecoration(labelText: 'නම'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else if(value.length < 4) {
                          return 'ඔබ යෙදූ නම කෙටි වැඩි ය.';}
                        return null;},
                      onSaved: (value) => _name = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(labelText: 'වයස (අවු. 18ට වැඩි විය යුතුයි)'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else if (int.parse(value)<18) {
                          return 'වයස අවුරුදු 18ට වැඩි විය යුතුයි';}
                        else if (int.parse(value) > 99) {
                          return 'සැබෑ වයසක් ඇතුළත් කරන්න';}
                        else {
                          return null;}},
                      onSaved: (value) => _age = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'ජාතික හැඳුනුම්පත් අංකය'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        //TODO finish regexp
                        String p =  r'(^[0-9]v|V|x|X$)';
                        RegExp regExp = new RegExp(p);
                        if (regExp.hasMatch(p) && value.length == 10 ) {
                          return null;}
                        else
                          return 'ඇතුළත් කල ජාතික හැඳුනුම්පත් අංකය වලංගු නොවේ';},
                      onSaved: (value) => _nic = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  child: Row(
                    children:[
                      SizedBox(
                        width: 100.0,
                        child: Text('ස්ත්‍රී / පුරුෂ භාවය :',
                          style: TextStyle(
                              color: Colors.black54,
                              fontSize: 16.0),),
                      ),
                      Expanded(
                        child: ListTile(
                          leading:Radio<String>(
                            value:'male',
                            groupValue: _sex,
                            activeColor: Colors.teal,
                            onChanged: (value) {
                              setState(() {_sex = value;});},),
                          title: const Text('පුරුෂ'),),
                      ),
                      Expanded(
                        child:  ListTile(
                        leading:Radio<String>(
                          value:'female',
                          groupValue: _sex,
                          activeColor: Colors.teal,
                          onChanged: (value) {setState(() {_sex = value;});},),
                        title: const Text('ස්ත්‍රී'),),),
                    ],
                  ),
                ),

                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'දුරකථන අංකය'),
                      validator: (value) {
                        String pattern = r'^[0-9]{10}$';
                        RegExp regExp = new RegExp(pattern);
                        if (value.length == 0) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else if (!regExp.hasMatch(value)) {
                          return 'ඉලක්කම් 10ක් සහිත 0න් ආරම්භ වන වලංගු දුරකථන අංකයක් \n ඇතුළත් කරන්න';}
                        else {return null;}},
                      onSaved: (value) => _telephone = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'ලිපිනය'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else {return null;}},
                      onSaved: (value) => _address = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'විද්‍යුත් ලිපිනය (තිබේනම්)'),
                      keyboardType: TextInputType.emailAddress,
                      validator: (value) {
                        String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" +
                            "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." +
                            "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+";
                        RegExp regExp = new RegExp(p);
                        if (value.isNotEmpty && !regExp.hasMatch(value)) {
                          return 'ඇතුළත් කල විද්‍යුත් ලිපිනය වලංගු නොවේ';}
                        else
                          return null;},
                      onSaved: (value) => _email = value)
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'අමතර කරුණු / විමසීම්'),
                      onSaved: (value) => _inquiry = value),
                ),

                Padding(padding: const EdgeInsets.fromLTRB(0, 0, 0, 25),),

                **DropdownButton<String>(
                  hint:Text ('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'),
                  icon: Icon(Icons.arrow_downward),
                  iconSize: 24, elevation: 16, style: TextStyle(color: Colors.teal),
                  underline: Container(height: 2, color: Colors.teal,),
                  onChanged: (String value) {setState(() {_branch = value;});},
                  items: <String>['Matara', 'Colombo','Galle'].map<DropdownMenuItem<String>>((String value){
                    return DropdownMenuItem<String>(value:value,
                        child: Text(value, style: TextStyle(fontSize: 20.0), textAlign: TextAlign.center,));}).toList(),),**
                Padding(padding: const EdgeInsets.fromLTRB(0, 0, 0, 45),),
                ElevatedButton (
                  onPressed: () {
                    if (_sex.isEmpty){
                      final message = 'ස්ත්‍රි පුරුෂ බව ඇතුළත් කරන්න';
                      final snackBar =  SnackBar(
                        content: Text(message),
                        backgroundColor:Colors.redAccent,
                        duration: Duration(milliseconds: 3000),);
                      ScaffoldMessenger.of(context).showSnackBar(snackBar);}
                    else
                    if (formKey.currentState.validate()){
                      formKey.currentState.save();
                      final message = '$_name, විමසීම සාර්ථකයි.';
                      final snackBar =  SnackBar(
                        content: Text(message),
                        backgroundColor:Colors.blue,
                        duration: Duration(milliseconds: 3000),);
                      ScaffoldMessenger.of(context).showSnackBar(snackBar);
                      return http.post(
                        Uri.parse('http://10.0.2.2:5000/api/userdata'),
                        headers: <String, String>{
                          'Content-Type': 'application/json; charset=UTF-8',},
                          body: jsonEncode(<String, String>{
                            'name': _name,
                            'age': _age,
                            'NIC': _nic,
                            'sex': _sex,
                            'tel': _telephone,
                            'addr': _address,
                            'email': _email,
                            'inquiry': _inquiry,
                            'branch': _branch
                          })
                      );
                    }},
                  child: Text('ඔබේ විමසීම මෙතැනින් අප වෙත යොමුකරන්න.'),
                )
               ]
              ),
            ),
      ));}

我尝试用按钮的“值”来解决_Branch _Branch并逆转名称,但它不起作用。然后,当我将_branch分配给teh下拉按钮的值属性时,它似乎有效,但是在重新加载屏幕时出现了错误

I have created a stateful customer information form and the there are two widgets that use the state - two list tiles with radio buttons and a drop down button. The list tiles respond to the code and updates their states and saves the data to the variable as expected.

But the drop down button only saves the value in the assigned variable, but does not display the new value instead of the hint.

I have followed sample code but as I'm new to Flutter I can't find where the mishap might be. Thank you for any help!

The code is as follows; please note that some of the label texts are in my native language and it wouldn't affect code readability. The code in question is in bold (**).

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class CustomerForm extends StatefulWidget {
  const CustomerForm({Key key}) : super(key: key);
  @override
  CustomerFormState createState() {
    return CustomerFormState();
  }}


class CustomerFormState extends State<CustomerForm> {
  final formKey = GlobalKey<FormState>();

  String _name = '';
  String _age = '';
  String _nic = '';
  String _sex = '';
  String _telephone = '';
  String _address = '';
  String _email = '';
  String _inquiry = '';
**String _branch = '';**




  @override
    Widget build(BuildContext context) => Scaffold(
      resizeToAvoidBottomInset : false,
     appBar: AppBar(
      title: Text('ඔබේ තොරතුරු පහත පුරවන්න',
      style: TextStyle(
      fontSize: (20.0),),),
      centerTitle: true,
      backgroundColor: Colors.cyan,
      shadowColor: Colors.tealAccent[50] ),
      body:SingleChildScrollView(
        child: Form(
            key: formKey,
              child: Column(children:[
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      autofocus: true,
                      decoration: InputDecoration(labelText: 'නම'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else if(value.length < 4) {
                          return 'ඔබ යෙදූ නම කෙටි වැඩි ය.';}
                        return null;},
                      onSaved: (value) => _name = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(labelText: 'වයස (අවු. 18ට වැඩි විය යුතුයි)'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        else if (int.parse(value)<18) {
                          return 'වයස අවුරුදු 18ට වැඩි විය යුතුයි';}
                        else if (int.parse(value) > 99) {
                          return 'සැබෑ වයසක් ඇතුළත් කරන්න';}
                        else {
                          return null;}},
                      onSaved: (value) => _age = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'ජාතික හැඳුනුම්පත් අංකය'),
                      validator: (value) {
                        if (value.isEmpty) {
                          return 'මෙම තොරතුරු අවශ්‍යයි';}
                        //TODO finish regexp
                        String p =  r'(^[0-9]v|V|x|X$)';
                        RegExp regExp = new RegExp(p);
                        if (regExp.hasMatch(p) && value.length == 10 ) {
                          return null;}
                        else
                          return 'ඇතුළත් කල ජාතික හැඳුනුම්පත් අංකය වලංගු නොවේ';},
                      onSaved: (value) => _nic = value),
                ),
                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 10, 10, 0),
                  child: Row(
                    children:[
                      SizedBox(
                        width: 100.0,
                        child: Text('ස්ත්‍රී / පුරුෂ භාවය :',
                          style: TextStyle(
                              color: Colors.black54,
                              fontSize: 16.0),),
                      ),
                      Expanded(
                        child: ListTile(
                          leading:Radio<String>(
                            value:'male',
                            groupValue: _sex,
                            activeColor: Colors.teal,
                            onChanged: (value) {
                              setState(() {_sex = value;});},),
                          title: const Text('පුරුෂ'),),
                      ),
                      Expanded(
                        child:  ListTile(
                        leading:Radio<String>(
                          value:'female',
                          groupValue: _sex,
                          activeColor: Colors.teal,
                          onChanged: (value) {setState(() {_sex = value;});},),
                        title: const Text('ස්ත්‍රී'),),),
                    ],
                  ),
                ),

                Padding(
                  padding: const EdgeInsets.fromLTRB(10, 0, 10, 0),
                  child: TextFormField(
                      decoration: InputDecoration(
                          labelText: 'දුරකථන අංකය'),
                      validator: (value) {
                        String pattern = r'^[0-9]{10}

I tried assigining _branch with 'value' of the button and reversing the names, it did not work. Then When I assigned _branch to the value attribute of teh drop down button it seemed to work but an error came on when the screen was reloaded

; RegExp regExp = new RegExp(pattern); if (value.length == 0) { return 'මෙම තොරතුරු අවශ්‍යයි';} else if (!regExp.hasMatch(value)) { return 'ඉලක්කම් 10ක් සහිත 0න් ආරම්භ වන වලංගු දුරකථන අංකයක් \n ඇතුළත් කරන්න';} else {return null;}}, onSaved: (value) => _telephone = value), ), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: TextFormField( decoration: InputDecoration( labelText: 'ලිපිනය'), validator: (value) { if (value.isEmpty) { return 'මෙම තොරතුරු අවශ්‍යයි';} else {return null;}}, onSaved: (value) => _address = value), ), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: TextFormField( decoration: InputDecoration( labelText: 'විද්‍යුත් ලිපිනය (තිබේනම්)'), keyboardType: TextInputType.emailAddress, validator: (value) { String p = "[a-zA-Z0-9\+\.\_\%\-\+]{1,256}" + "\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" + "\\." + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,25}" + ")+"; RegExp regExp = new RegExp(p); if (value.isNotEmpty && !regExp.hasMatch(value)) { return 'ඇතුළත් කල විද්‍යුත් ලිපිනය වලංගු නොවේ';} else return null;}, onSaved: (value) => _email = value) ), Padding( padding: const EdgeInsets.fromLTRB(10, 0, 10, 0), child: TextFormField( decoration: InputDecoration( labelText: 'අමතර කරුණු / විමසීම්'), onSaved: (value) => _inquiry = value), ), Padding(padding: const EdgeInsets.fromLTRB(0, 0, 0, 25),), **DropdownButton<String>( hint:Text ('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'), icon: Icon(Icons.arrow_downward), iconSize: 24, elevation: 16, style: TextStyle(color: Colors.teal), underline: Container(height: 2, color: Colors.teal,), onChanged: (String value) {setState(() {_branch = value;});}, items: <String>['Matara', 'Colombo','Galle'].map<DropdownMenuItem<String>>((String value){ return DropdownMenuItem<String>(value:value, child: Text(value, style: TextStyle(fontSize: 20.0), textAlign: TextAlign.center,));}).toList(),),** Padding(padding: const EdgeInsets.fromLTRB(0, 0, 0, 45),), ElevatedButton ( onPressed: () { if (_sex.isEmpty){ final message = 'ස්ත්‍රි පුරුෂ බව ඇතුළත් කරන්න'; final snackBar = SnackBar( content: Text(message), backgroundColor:Colors.redAccent, duration: Duration(milliseconds: 3000),); ScaffoldMessenger.of(context).showSnackBar(snackBar);} else if (formKey.currentState.validate()){ formKey.currentState.save(); final message = '$_name, විමසීම සාර්ථකයි.'; final snackBar = SnackBar( content: Text(message), backgroundColor:Colors.blue, duration: Duration(milliseconds: 3000),); ScaffoldMessenger.of(context).showSnackBar(snackBar); return http.post( Uri.parse('http://10.0.2.2:5000/api/userdata'), headers: <String, String>{ 'Content-Type': 'application/json; charset=UTF-8',}, body: jsonEncode(<String, String>{ 'name': _name, 'age': _age, 'NIC': _nic, 'sex': _sex, 'tel': _telephone, 'addr': _address, 'email': _email, 'inquiry': _inquiry, 'branch': _branch }) ); }}, child: Text('ඔබේ විමසීම මෙතැනින් අප වෙත යොමුකරන්න.'), ) ] ), ), ));}

I tried assigining _branch with 'value' of the button and reversing the names, it did not work. Then When I assigned _branch to the value attribute of teh drop down button it seemed to work but an error came on when the screen was reloaded

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

动次打次papapa 2025-01-25 01:45:36

这可能会有所帮助:


DropdownButton(
  hint: Text('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'),
  icon: Icon(Icons.arrow_downward),
  iconSize: 24,
  value: _branch,
  elevation: 16,
  style: TextStyle(color: Colors.teal),
  underline: Container(
    height: 2,
    color: Colors.teal,
  ),
  onChanged: (value) async {
    setState(() {
      _branch = value;
      debugPrint(value);
    });
  },
  items: <String>['Matara', 'Colombo', 'Galle']
      .map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
        value: value,
        child: Text(
          value,
          style: TextStyle(fontSize: 20.0),
          textAlign: TextAlign.center,
        ));
  }).toList(),
),

您要在下拉式窗口小部件内声明“值”,如果您希望从下拉菜单中选择选项后立即出现文本,则必须这样使用。
我猜如果您更改后有问题,也许它与下拉餐点无关。

This might help you out:


DropdownButton(
  hint: Text('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'),
  icon: Icon(Icons.arrow_downward),
  iconSize: 24,
  value: _branch,
  elevation: 16,
  style: TextStyle(color: Colors.teal),
  underline: Container(
    height: 2,
    color: Colors.teal,
  ),
  onChanged: (value) async {
    setState(() {
      _branch = value;
      debugPrint(value);
    });
  },
  items: <String>['Matara', 'Colombo', 'Galle']
      .map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
        value: value,
        child: Text(
          value,
          style: TextStyle(fontSize: 20.0),
          textAlign: TextAlign.center,
        ));
  }).toList(),
),

You'vent declared the "value" inside the DropdownButton widget, if you want your text to appear soon as you choose an option from the Dropdown you must use it like this.
I guess if there's a problem after you change it maybe it's not related to dropdownbutton.

彩扇题诗 2025-01-25 01:45:36

这可能非常有帮助

final List<String> _items = ['Matara', 'Colombo','Galle'];
late String _branch = _items[0]; //Default selected value


DropdownButton(
    hint: Text('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'),
    icon: Icon(Icons.arrow_downward),
    iconSize: 24,
    value: _branch,
    elevation: 16,
    style: TextStyle(color: Colors.teal),
    underline: Container(
       height: 2,
       color: Colors.teal,
    ),
    onChanged: (value) async {
       setState(() {
           _branch = value;
           debugPrint(value);
       });
    },
    items:_items.map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
             value: value,
             child: Text(
                 value,
                 style: TextStyle(fontSize: 20.0),
                 textAlign: TextAlign.center,
               )
            );
    }).toList(),
),

This could be very helpful

final List<String> _items = ['Matara', 'Colombo','Galle'];
late String _branch = _items[0]; //Default selected value


DropdownButton(
    hint: Text('ඔබට ළඟම බැංකු ශාඛාව මෙතනින් තෝරන්න.'),
    icon: Icon(Icons.arrow_downward),
    iconSize: 24,
    value: _branch,
    elevation: 16,
    style: TextStyle(color: Colors.teal),
    underline: Container(
       height: 2,
       color: Colors.teal,
    ),
    onChanged: (value) async {
       setState(() {
           _branch = value;
           debugPrint(value);
       });
    },
    items:_items.map<DropdownMenuItem<String>>((String value) {
    return DropdownMenuItem<String>(
             value: value,
             child: Text(
                 value,
                 style: TextStyle(fontSize: 20.0),
                 textAlign: TextAlign.center,
               )
            );
    }).toList(),
),
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文