【问题标题】:Flutter - How to enable TextFormField using Switch buttonFlutter - 如何使用 Switch 按钮启用 TextFormField
【发布时间】:2021-01-11 10:21:44
【问题描述】:

我禁用了 TextFormField,我想使用自定义开关再次启用它。包裹是here 这是代码

bool isEnabled = false;

CustomSwitch(
   activeColor: Colors.greenAccent,
   value: isEnabled,
   onChanged: (value) {
      setState(() {
         isEnabled = value;
      });
   },
),


TextFormField(
   enabled: isEnabled,
   decoration: InputDecoration(labelText: 'Name'),
   
),

您知道如何使用切换按钮启用/禁用文本表单字段吗? 如果我使用复选框而不是开关也没关系。蒂亚!

【问题讨论】:

  • 上面的代码sn-p不行吗?
  • 是的,开关正在工作,它可以启用和禁用,但当开关打开/关闭时,文本表单字段无法启用/禁用。它保持禁用/错误
  • 这两个小部件是否都显示在同一屏幕上?如果是,那么 enabled 参数应该按预期工作。
  • 不在AS前面但是设置状态调用不应该是isEnabled != isEnabled从真到假再切换吗?
  • 是的@MaadhavSharma。它在同一个屏幕上。

标签: flutter flutter-web


【解决方案1】:

这段代码 sn-p 对我来说很好用。

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  bool status = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Custom Switch Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            CustomSwitch(
              activeColor: Colors.pinkAccent,
              value: status,
              onChanged: (value) {
                print("VALUE : $value");
                setState(() {
                  status = value;
                });
              },
            ),
            SizedBox(height: 12.0,),
            Text('Value : $status', style: TextStyle(
              color: Colors.black,
              fontSize: 20.0
            ),),
            SizedBox(height: 12.0,),
            TextFormField(
          enabled: status,
          decoration: InputDecoration(
              labelText: 'Name', disabledBorder: InputBorder.none),
        )
          ],
        ),
      ),
    );
  }
}

【讨论】:

  • 啊.. 我明白了,也许问题是我的 CustomSwitch 而 TextFormField 在 AlertDialog 内。谢谢!
  • @CodeFloat True,Alert Dialogue 是一个无状态小部件。要在其中设置状态,您需要在警报对话中使用 StatefulBuilder。如果需要帮助,请告诉我
猜你喜欢
  • 1970-01-01
  • 2021-04-07
  • 1970-01-01
  • 1970-01-01
  • 2022-12-18
  • 2021-06-25
  • 2021-02-17
  • 2021-10-05
  • 2019-01-25
相关资源
最近更新 更多