【问题标题】:TextField & BLoC : pre-filling a fieldTextField & BLoC : 预填充字段
【发布时间】:2021-02-20 18:55:32
【问题描述】:

我有一个带有表单的屏幕,我用它来发布广告,并使用同一个屏幕来编辑广告。当我想编辑广告时,表单会预先填写广告内容。我通过将要显示的文本提供给 TextEditingController 来做到这一点。

同时,我使用 BLoC 模式来管理我的应用程序的业务逻辑,并在 Textfield 的 onChange 属性中生成一个新状态。因此,每次更改都会生成文本字段,因此还会生成 TextEditingController,以防止我更改字段的文本。

 TextField(
      controller: isUpdate ? 
        TextEditingController(
          text: isUpdate == true ? myAd.property.toString() //as it builds at every single change, the text can't be modified 
            : null,
        ): null,
      onChanged: (newValue) {
         context.read<MyBloc>().add(TitleChanged(value: newValue))

那么有没有办法让我预先填写该字段,但只填写一次 - 不是在每个构建中 - 以便我可以继续编辑它?

【问题讨论】:

    标签: flutter dart textfield bloc


    【解决方案1】:

    您可以将文本作为字符串包含在您的 Blocs 状态中,因此您可以使用 state.formText 而不是使用 myAd.property.toString()。 每当您使用 TitleChangedevent 更改表单时,您也会更新您所在区域中的 formText。

    【讨论】:

      【解决方案2】:

      更改代码以使用 TextFormField 并设置 initialValue

       TextFormField(
            initialValue: isUpdate ? myAd.property.toString(): null,
            onChanged: (newValue) {
               context.read<MyBloc>().add(TitleChanged(value: newValue))
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-24
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多