【问题标题】:Flutter TextFormField initial value not workingFlutter TextFormField 初始值不起作用
【发布时间】:2020-06-14 04:07:50
【问题描述】:

如果在我的文本表单字段上创建了一个初始值,我正在尝试设置一个初始值。当我运行我的代码时:

final apiField = TextFormField(
  controller: apiFieldController,
  initialValue: _read().toString(),
  obscureText: true,
  style: style,
  decoration: InputDecoration(
      contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
      hintText: "API Key",
      border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
);

_read() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
//Return String
String stringValue = prefs.getString('apiKey') ?? '';
return stringValue;
}

我收到以下错误:

package:flutter/src/material/text_form_field.dart: failed assertion. initial value == null || controller == null is not true

我不确定自己被困在哪里。我确实看到控制器正在初始化。我相信我的 _read() 方法有问题,但它确实返回了一个字符串。

【问题讨论】:

  • 用 FutureBuilder 包装并提供初始值为 ""

标签: flutter dart


【解决方案1】:

可能是因为您设置了控制器和初始值。您只需设置这些属性之一。或初始值或控制器。

【讨论】:

    【解决方案2】:
    var _formKey = GlobalKey<FormState>();
    Map<String, String> map = {
        'Name': '',
    };
    

    内部 小部件构建(BuildContext 上下文)

     Form(
      key: _formKey,
      child: Column(
        children: <Widget>[
          TextFormField(
            key: map['Name'].isEmpty
              ? Key('Name')
              : Key(map['Name']),
            initialValue: map['Name'],
            onSaved: (value) {
              map['Name'] = value.trim();
            },
          ),
        ],
      ),
    ),
    

    【讨论】:

      【解决方案3】:

      您的 read() 返回 Future&lt;string&gt; 而不是字符串。 您需要使用setState 方法将initial value 直接设置为控制器

      我还建议您在项目中安装静态分析以避免此类问题 https://dart.dev/guides/language/analysis-options

      【讨论】:

      【解决方案4】:

      您可以在 TextFormField 中建立初始值:

      TextFormField(
        initialValue: "Initial String",
      

      或者您可以使用 TextEditingController 建立它:

      TextEditingController(text:"Initial String");
      

      但你不能两者都做,这会导致字段断言错误:

      Failed assertion: line 196 pos 15: 'initialValue == null || controller == null': is not true.
      

      我更喜欢在持有表单的小部件的 initState 中为控制器设置一个初始值。

      【讨论】:

        猜你喜欢
        • 2020-12-01
        • 1970-01-01
        • 2020-10-18
        • 1970-01-01
        • 2023-01-12
        • 2021-06-19
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多