【问题标题】:How to change TextFormField initialValue dynamically?如何动态更改 TextFormField 的初始值?
【发布时间】:2021-10-13 16:30:40
【问题描述】:

我正在尝试使用提供程序模型中的值来更新 TextFormField 的 initialValue,但 initialValue 没有改变。


import 'package:flutter/material.dart';
import 'package:new_app/models/button_mode.dart';
import 'package:provider/provider.dart';

class EditWeightTextField extends StatelessWidget {


  const EditWeightTextField(
      {Key? key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
  
    return Consumer<ButtonMode>(builder: (context, buttonMode, child) {
        return TextFormField(
            initialValue: buttonMode.weight.toString(),
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter weight';
              }
              return null;
            },
         
              );
    });
  }
}

如果我使用 Text(${buttonMode.weight}') 而不是 TextFormField,则文本会正确更新。我该怎么做才能使它与 TextFormField 一起使用?

【问题讨论】:

  • 我建议您使用TextEditingController(text: 'Initial value'); ,如果您需要完整的解决方案,请告诉我
  • 我希望有一个完整的解决方案

标签: flutter flutter-provider


【解决方案1】:

在这种情况下,您可以使用 TextEditingController。

TextEditingController _controller = TextEditingController();

Consumer<ButtonMode>(builder: (context, buttonMode, child) {

        if(buttonMode.weight != null && _controller.text != buttonMode.weight){ // or check for the null value of button mode.weight alone
             _controller.text = buttonMode.weight ?? '' ;
        }
        return TextFormField(
            controller : _controller,
            validator: (value) {
              if (value == null || value.isEmpty) {
                return 'Please enter weight';
              }
              return null;
            },
         
              );
    });

【讨论】:

    猜你喜欢
    • 2019-09-29
    • 1970-01-01
    • 2020-12-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 2020-06-14
    • 2020-11-11
    相关资源
    最近更新 更多