Flutter Checkbox with the radio button logic

Issue

I have been trying to get the radio button functionality using checkboxes in flutter but I could not come up with a solution for this issue. Most of the examples I come across are with the ability to select multiple checkboxes.

Solution

Please check the bellow code.

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

int index = 0;

class demo extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _demoState();
}

class _demoState extends State<demo> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: SafeArea(
        child: ListView.builder(
          itemCount: 6,
          itemBuilder: (context, i) {
            return GestureDetector(
              onTap: () {
                setState(() {
                  index = i;
                });
              },
              child: ListTile(
                leading: index == i
                    ? Icon(Icons.check_box)
                    : Icon(Icons.check_box_outline_blank),
                title: Text(i.toString()),
              ),
            );
          },
        ),
      ),
    );
  }
}

Answered By – Salim Murshed

Answer Checked By – Dawn Plyler (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.