Flutter : Custom Radio Button

前端 未结 4 1225
挽巷
挽巷 2020-12-08 05:44

How can I create a custom radio button group like this in flutter

4条回答
  •  不知归路
    2020-12-08 06:02

    I achieved that with the following logic. reply if you need a detailed explanation

    import 'package:flutter/material.dart';
    
    class Parent extends StatefulWidget {
      Parent({
        Key key,
      }) : super(key: key);
    
      @override
      _ParentState createState() => _ParentState();
    }
    
    class _ParentState extends State {
      int _selectedItem = 0;
    
      selectItem(index) {
        setState(() {
          _selectedItem = index;
          print(selectItem.toString());
        });
      }
    
      @override
      Widget build(BuildContext context) {
        //...YOUR WIDGET TREE HERE
    
        return ListView.builder(
          shrinkWrap: true,
          itemCount: 5,
          itemBuilder: (context, index) {
            return CustomItem(
              selectItem, // callback function, setstate for parent
              index: index,
              isSelected: _selectedItem == index ? true : false,
              title: index.toString(),
            );
          },
        );
      }
    }
    
    class CustomItem extends StatefulWidget {
      final String title;
      final int index;
      final bool isSelected;
      Function(int) selectItem;
    
      CustomItem(
        this.selectItem, {
        Key key,
        this.title,
        this.index,
        this.isSelected,
      }) : super(key: key);
    
      _CustomItemState createState() => _CustomItemState();
    }
    
    class _CustomItemState extends State {
      @override
      Widget build(BuildContext context) {
        return Row(
          children: [
            Text("${widget.isSelected ? "true" : "false"}"),
            RaisedButton(
              onPressed: () {
                widget.selectItem(widget.index);
              },
              child: Text("${widget.title}"),
            )
          ],
        );
      }
    }
    

提交回复
热议问题