颤动:自定义单选按钮

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了颤动:自定义单选按钮相关的知识,希望对你有一定的参考价值。

如何在flutter custom radio in flutter中创建这样的自定义单选按钮组

答案

这是完整的代码

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);
}

使用:

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

屏幕截图:enter image description here

另一答案

您可以使用ListView和List Item创建它,并使用一个局部变量来存储所选项目。您可以根据变量渲染选定的ListItem。

附:如果您需要代码段,请告诉我们。

[编辑]

正如您所要求的,这里是代码片段,它将向您展示如何维护每个ListView项的状态。

现在你可以玩它,并按照你想要的方式。如果您只想要一个选定的项目,则可以按此方式编写逻辑。

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"),
        )
      ],
    );
  }
}
另一答案

我用以下逻辑实现了这一点。如果您需要详细解释,请回复

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}"),
        )
      ],
    );
  }
}

以上是关于颤动:自定义单选按钮的主要内容,如果未能解决你的问题,请参考以下文章

颤动单选按钮的问题

如何在颤动中获得这种单选按钮

颤动验证单选按钮

如何在颤动中将图标放在自定义按钮内

颤动中的单选按钮活动颜色不起作用

当用户从颤动的单选按钮组中选择单选按钮时如何保存数据?