Flutter textField 自动设置状态

问题描述 投票:0回答:1

我在

RadioListTile
中有一个
DraggableScrollabeSheet
列表。当我点击 RadioListTile 之一时,会出现一个 TextField。但我立即点击文本字段,得到 SetState 响应,并且选项返回到选项 1。所以我无法在文本字段中输入任何内容。

List<String> options1 = [
      "A",
      "B",
      "C",
      "D",
      "Others"
     ...
    ];
    String currentOption = options[0];

Column(
  children:[
     RadioListTile(
      activeColor: Colors.red,
      title: Text("A"),
      value: options[0],
      groupValue: currentOption,
      onChanged: (value){
          setState((){
           currentOption = value.toString();
         })
        }
      )
.....//This continues till the last option

     //Then if the last option (Other) is chosen, a textfield is displayed
     
    currentOption == options[4]?
     TextField(
         .....
         ):SizedBox(),

     ]
   )

因此,当我点击文本字段时,它会设置状态并且当前选项移回到

options[0]

flutter radio-button
1个回答
0
投票

发生这种情况是因为您在

build
方法中声明了变量,每次尝试更新 UI 时都会重置变量值(当您调用
setState
时)

您可以在这里做的是初始化

initState
中的变量,这将解决您的问题

这是示例:

class SheetView extends StatefulWidget {
  const SheetView({
    super.key,
  });

  @override
  State<SheetView> createState() => _SheetViewState();
}

class _SheetViewState extends State<SheetView> {
  late String currentOption;
  List<String> options1 = [
      "A",
      "B",
      "C",
      "D",
      "Others"
    ];

@override
void initState() {
/// This will be called before UI is created
currentOption = options[0];
    super.initState();
}

  @override
  Widget build(BuildContext context) {
    return Column(
  children:[
     RadioListTile(
      activeColor: Colors.red,
      title: Text("A"),
      value: options[0],
      groupValue: currentOption,
      onChanged: (value){
          setState((){
           currentOption = value.toString();
         })
        }
      ),

     //This continues till the last option
     //Then if the last option (Other) is chosen, a textfield is displayed
     
    currentOption == options[4] ?
     TextField(
         .....
         ) : SizedBox(),
     ]
   );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.