Flutter : Custom Radio Button

前端 未结 4 1216
挽巷
挽巷 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<Parent> {
      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<CustomItem> {
      @override
      Widget build(BuildContext context) {
        return Row(
          children: <Widget>[
            Text("${widget.isSelected ? "true" : "false"}"),
            RaisedButton(
              onPressed: () {
                widget.selectItem(widget.index);
              },
              child: Text("${widget.title}"),
            )
          ],
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-08 06:03

    You can create it with ListView and List Item with one local variable to store the selected item. And you can render the selected the ListItem based on the variable.

    P.S. Let me know if you need code snippet.

    [EDIT]

    As you have requested, Here is code snipper which will show you how you can maintain the state of each ListView item.

    Now you can play with it and make it the way you want. If you want only one selected item you can write the logic that way.

    void main() {
      runApp(new MaterialApp(
        home: new ListItemDemo(),
      ));
    }
    
    class ListItemDemo extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("ListItem"),
          ),
          body: new ListView.builder(
              itemCount: 10,
              itemBuilder: (BuildContext context, int index) {
                return new MyListItem(
                  title: "Hello ${index + 1}",
                );
              }),
        );
      }
    }
    
    class MyListItem extends StatefulWidget {
      final String title;
    
      MyListItem({this.title});
    
      @override
      _MyListItemState createState() => new _MyListItemState();
    }
    
    class _MyListItemState extends State<MyListItem> {
      bool isSelected;
    
      @override
      void initState() {
        super.initState();
        isSelected = false;
      }
    
      @override
      Widget build(BuildContext context) {
        return new Row(
          children: <Widget>[
            new Text("${widget.title} ${isSelected ? "true" : "false"}"),
            new RaisedButton(
              onPressed: () {
                if (isSelected) {
                  setState(() {
                    isSelected = false;
                  });
                } else {
                  setState(() {
                    isSelected = true;
                  });
                }
              },
              child: new Text("Select"),
            )
          ],
        );
      }
    }
    
    0 讨论(0)
  • 2020-12-08 06:05
    import 'package:flutter/material.dart';
    class CustomRadio extends StatefulWidget {
      @override
      createState() {
        return new CustomRadioState();
      }
    }
    
    class CustomRadioState extends State<CustomRadio> {
      List<RadioModel> sampleData = new List<RadioModel>();
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        sampleData.add(new RadioModel(true, 'A',0xffe6194B));
        sampleData.add(new RadioModel(false, 'B',0xfff58231));
        sampleData.add(new RadioModel(false, 'C',0xffffe119));
        sampleData.add(new RadioModel(false, 'D',0xffbfef45));
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("ListItem"),
          ),
          body: new ListView.builder(
            itemCount: sampleData.length,
            itemBuilder: (BuildContext context, int index) {
              return new InkWell(
                splashColor: Colors.blueAccent,
                onTap: () {
                  setState(() {
                    sampleData.forEach((element) => element.isSelected = false);
                    sampleData[index].isSelected = true;
                  });
                },
                child: new RadioItem(sampleData[index]),
              );
            },
          ),
        );
      }
    }
    
    class RadioItem extends StatelessWidget {
      final RadioModel _item;
      RadioItem(this._item);
      @override
      Widget build(BuildContext context) {
        return new Container(
          margin: new EdgeInsets.all(15.0),
          child: new Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              new Container(
                height: 25.0,
                width: 25.0,
                alignment: Alignment.center,
                child:Container(
                height: 15.0,
                width: 15.0,
                  decoration: new BoxDecoration(
                  color:Color(_item.colorCode),
                  borderRadius: const BorderRadius.all(const Radius.circular(15)),
                )
    
                ),
                decoration: new BoxDecoration(
                  color: Colors.transparent,
                  border: new Border.all(
                      width: 3.0,
                      color: _item.isSelected
                          ? Color(_item.colorCode)
                          : Colors.transparent),
                  borderRadius: const BorderRadius.all(const Radius.circular(25)),
                ),
              ),
              new Container(
                margin: new EdgeInsets.only(left: 10.0)
              )
            ],
          ),
        );
      }
    }
    
    class RadioModel {
      bool isSelected;
      final String buttonText;
      final int colorCode;
    
      RadioModel(this.isSelected, this.buttonText,this.colorCode);
    }
    void main() {
      runApp(new MaterialApp(
        home: new CustomRadio(),
      ));
    }
    

    Click here to check out put-> Here

    0 讨论(0)
  • 2020-12-08 06:09

    Here is the full code

    class CustomRadio extends StatefulWidget {
      @override
      createState() {
        return new CustomRadioState();
      }
    }
    
    class CustomRadioState extends State<CustomRadio> {
      List<RadioModel> sampleData = new List<RadioModel>();
    
      @override
      void initState() {
        // TODO: implement initState
        super.initState();
        sampleData.add(new RadioModel(false, 'A', 'April 18'));
        sampleData.add(new RadioModel(false, 'B', 'April 17'));
        sampleData.add(new RadioModel(false, 'C', 'April 16'));
        sampleData.add(new RadioModel(false, 'D', 'April 15'));
      }
    
      @override
      Widget build(BuildContext context) {
        return new Scaffold(
          appBar: new AppBar(
            title: new Text("ListItem"),
          ),
          body: new ListView.builder(
            itemCount: sampleData.length,
            itemBuilder: (BuildContext context, int index) {
              return new InkWell(
                //highlightColor: Colors.red,
                splashColor: Colors.blueAccent,
                onTap: () {
                  setState(() {
                    sampleData.forEach((element) => element.isSelected = false);
                    sampleData[index].isSelected = true;
                  });
                },
                child: new RadioItem(sampleData[index]),
              );
            },
          ),
        );
      }
    }
    
    class RadioItem extends StatelessWidget {
      final RadioModel _item;
      RadioItem(this._item);
      @override
      Widget build(BuildContext context) {
        return new Container(
          margin: new EdgeInsets.all(15.0),
          child: new Row(
            mainAxisSize: MainAxisSize.max,
            children: <Widget>[
              new Container(
                height: 50.0,
                width: 50.0,
                child: new Center(
                  child: new Text(_item.buttonText,
                      style: new TextStyle(
                          color:
                              _item.isSelected ? Colors.white : Colors.black,
                          //fontWeight: FontWeight.bold,
                          fontSize: 18.0)),
                ),
                decoration: new BoxDecoration(
                  color: _item.isSelected
                      ? Colors.blueAccent
                      : Colors.transparent,
                  border: new Border.all(
                      width: 1.0,
                      color: _item.isSelected
                          ? Colors.blueAccent
                          : Colors.grey),
                  borderRadius: const BorderRadius.all(const Radius.circular(2.0)),
                ),
              ),
              new Container(
                margin: new EdgeInsets.only(left: 10.0),
                child: new Text(_item.text),
              )
            ],
          ),
        );
      }
    }
    
    class RadioModel {
      bool isSelected;
      final String buttonText;
      final String text;
    
      RadioModel(this.isSelected, this.buttonText, this.text);
    }
    

    To use :

    void main() {
      runApp(new MaterialApp(
        home: new CustomRadio(),
      ));
    }
    

    Screenshot :

    0 讨论(0)
提交回复
热议问题