簡體   English   中英

setState 不適用於 Flutter 中的 DropDown 按鈕

[英]setState is not working with DropDown Button in Flutter

當我從下拉列表中選擇數量時,我正在根據數量計算總量,但總量Textformfield保持不變,當我調試代碼時,我在setState方法中獲得更新的數量,但沒有反映在 UI 上,我也是從它正在工作的方法中的另一種方法更新總數。

 class _ProductDetailsPageState extends State<ProductDetailsPage> {


  List _quantity = ["1", "2", "3", "4", "5"];
  List<DropdownMenuItem<String>> _dropDownQuantity;

  String _currentQuantity;
  String _productprice;
  double _taxrateamt;
  double _taxper = 0.0;
  String _producttotal;
  int _productqty;
  double _discount = 3.0;
  String _productname;

  List<DropdownMenuItem<String>> getDropDownQuantity() {
    List<DropdownMenuItem<String>> items = new List();
    for (String city in _quantity) {
      items.add(new DropdownMenuItem(
          value: city,
          child: new Text(
            city,
            style:
                TextStyle(color: MyColors.colorPrimary, fontFamily: 'semibold'),
          )));
    }
    return items;
  }

  @override
  void initState() {
    super.initState();

    _dropDownQuantity = getDropDownQuantity();
    _currentQuantity = _dropDownQuantity[0].value;
  }

  Container rateAndTotal( String value) {
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                flex: 1,
                child: Container(
                  child: TextFormField(
                    style: TextStyle(
                        fontFamily: 'medium', color: MyColors.colorPrimaryDark),
                    keyboardType: TextInputType.number,
                    enabled: false,
                    textInputAction: TextInputAction.done,
                    initialValue: '${value}',
                    decoration: InputDecoration(
                        border: InputBorder.none, hintText: '$value'),),),),],),],),);}

  Container quantity() {
    return Container(
      child: Column(
        children: <Widget>[
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: <Widget>[
              Expanded(
                flex:1,
                child: Container(
                     child: DropdownButtonHideUnderline(
                      child: DropdownButton(
                        value: _currentQuantity,
                        items: _dropDownQuantity,
                        onChanged: changedDropDownQuantity,),)),),],),],),);}

  @override
  Widget build(BuildContext context) {

        MediaQueryData queryData;
        queryData = MediaQuery.of(context);
        double width = queryData.size.width;
        double height = queryData.size.height;

        return new Container(
          height: double.infinity,
          decoration: BoxDecoration(color: Colors.grey[200]),
          child: SingleChildScrollView(
            child: Container(
              padding: EdgeInsets.all(height * 0.020),
              child: Column(
                children: <Widget>[
                  quantity(),
                  rateAndTotal( '${_productprice}'),
                ],
              ),
            ),
          ),
        );
  }

  void changedDropDownQuantity(String selected_quantity) {
    setState(() {
      _currentQuantity = selected_quantity;
      // _producttotal=getProductTotal(_productprice,_currentQuantity);
    });

    setState(() {
      _producttotal=getProductTotal(_productprice,_currentQuantity);
    });

  }

  String getProductTotal(String productprice, String _currentQuantity) {
    try {

      double sprice = 0.0;
      double total = double.parse(productprice);
      double taxrate = _taxrateamt;
      double qty = double.parse(_currentQuantity);

      return _producttotal =
          (((total + taxrate + sprice) - _discount) * qty).toString();
    } catch (e) {
      debugPrint('PRODUCT TOTAl EXC.:--${e}');

      return _producttotal = productprice;
    }
  }
}

在此處輸入圖片說明

要解決此問題,請替換 TextFormField 中的以下行:

initialValue: '$value',

和:

controller: TextEditingController(text: value),

或者更好:

// Define a controller in the State
class _ProductDetailsPageState extends State<ProductDetailsPage> {
  TextEditingController _controller = TextEditingController(text: value);

  ...
  // Then bind that controller to your TextFormField, replacing initialValue
    child: TextFormField(
      controller: _controller,

  ...

  // Then change the .text property of that controller when you want it to update
  setState(() => _controller.text = value);

initialValue僅用於設置第一次初始化StateTextFormField第一個值是什么,並且State通過重建保留,因此覆蓋它永遠不會導致文本更改。

重寫TextEditingController每次完全或定義TextEditingController和改變.text屬性將正確地傳遞改變了State的領域,並更新你的價值。

另一種情況; 如果在彈出窗口中使用下拉按鈕,則需要使用 StatefulBuilder。 這是參考; 如何在 Flutter 中刷新 AlertDialog?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM