0

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]

1 Answer 1

1

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(),
     ]
   );
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot. I was struggling with it for a long time. It helped a lot. Thanks, once again

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.