flutterradio-button

Flutter textField automatically sets state


I have a list of RadioListTile in a DraggableScrollabeSheet. When I tap on one of the RadioListTile, a TextField appears. But immediately I tap on the textField, I get a SetState response and option goes back to option 1. So I can't type anything in the TextField.

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(),

     ]
   )

So this is where when I tap on the textfield, it sets state and the current option moves back to options[0]


Solution

  • This is happening because you have declared variables inside build method which resets variable value each time you try to update UI (when you call setState)

    What you can do here is initialise your variables in initState which will fix your issue

    here is the example how it should be:

    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(),
         ]
       );
      }
    }