Flutter radiolisttile validation

Flutter RadioListTile Validation

In Flutter, you can use the RadioListTile widget to create a group of radio buttons. Each radio button can have its own value and label. To add validation to the RadioListTile group, you can make use of the Form and TextFormField widgets provided by the Flutter framework.

Here’s an example of how you can implement validation for a RadioListTile group:

  
import 'package:flutter/material.dart';

class MyForm extends StatefulWidget {
  @override
  _MyFormState createState() => _MyFormState();
}

class _MyFormState extends State {
  String _selectedValue;
  GlobalKey _formKey = GlobalKey();

  @override
  Widget build(BuildContext context) {
    return Form(
      key: _formKey,
      child: Column(
        children: [
          RadioListTile(
            title: Text('Option 1'),
            value: 'Option 1',
            groupValue: _selectedValue,
            onChanged: (value) {
              setState(() {
                _selectedValue = value;
              });
            },
          ),
          RadioListTile(
            title: Text('Option 2'),
            value: 'Option 2',
            groupValue: _selectedValue,
            onChanged: (value) {
              setState(() {
                _selectedValue = value;
              });
            },
          ),
          RaisedButton(
            child: Text('Submit'),
            onPressed: () {
              if (_formKey.currentState.validate()) {
                _formKey.currentState.save();
                // Do something with the selected value
              }
            },
          ),
        ],
      ),
    );
  }
}

void main() {
  runApp(MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('RadioListTile Validation'),
      ),
      body: MyForm(),
    ),
  ));
}
  
  

In this example, we create a StatefulWidget called MyForm. We initialize a _selectedValue variable to keep track of the selected radio button’s value. Then, we create a GlobalKey to associate with the Form widget.

Inside the build method, we wrap our Column of RadioListTiles with the Form widget and set the key to _formKey. Each RadioListTile has its own title, value, groupValue, and onChanged properties. The groupValue property should be set to the _selectedValue and onChanged should call setState to update the value when a radio button is selected.

We also have a RaisedButton at the end of the Column to submit the form. When the button is pressed, we check if the form is valid using _formKey.currentState.validate(). If the form is valid, we can save the form data and perform any desired actions.

Note: You may need to import the necessary packages (e.g. material.dart) for the code to work properly.

Hope this helps explain how to add validation to a RadioListTile group in Flutter! Let me know if you have any further questions.

Leave a comment