setState не работает с кнопкой DropDown в Flutter

1

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

 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;
    }
  }
}

Изображение 174551

Теги:
flutter
dart

1 ответ

1
Лучший ответ

Чтобы это исправить, замените строку ниже в вашем 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 только используется, чтобы установить, что само первое значение TextFormField будет, когда State является первым инициализирован, и State сохраняется через перестраивает так перекрывая никогда не заставит текст изменить.

Переопределение TextEditingController полностью каждый раз, или определения TextEditingController и изменения .text свойства будет правильно передать изменения в State поля и обновить значение.

  • 0
    спасибо, это работает.

Ещё вопросы

Сообщество Overcoder
Наверх
Меню