如何在 Flutter 中的 onPressed 方法中获取 radioButton 值



我正在尝试使用 Flutter 编写购物应用程序的更简单版本,但在编写我拥有的按钮的 onPressed 方法时遇到了问题,该方法应该包含单击的单选按钮的值(我有三个单选按钮(,以便根据其值,它将导航到不同的页面。下面是描述应用程序第一页的类

类 MyAppState 扩展状态

{ int _selected = 0;

void onPressed()
{
     //what to write??
}
void onChanged(int value)
{
    setState(() {
        _selected = value;
    });
}
List<Widget> makeRadios()
{
    List<Widget> list = new List<Widget>();
    List names = new List(3);
    names[0]="Women";
    names[1]="Men";
    names[2]="Children";
    list.add(new Text(
        "Category:",
        style: TextStyle(
            decoration: TextDecoration.underline,
            fontSize: 25,
            color: Colors.deepPurple,
        ),
    ));
    for(int i=0;i<3;i++)
    {
        list.add(
            new RadioListTile(
                value: i,
                title: Text(names[i]),
                groupValue: _selected,
                onChanged: (int value){onChanged(value);},
                activeColor: Colors.deepPurple,
                secondary: new Icon(Icons.shopping_basket),
            ));
    }
    list.add(new RaisedButton(
        child: new Text(
            "done!",
            style: TextStyle(
                fontSize :17.0,
                color: Colors.white,
            ),
        ),
        color:Colors.purpleAccent,
        onPressed: onPressed,
        shape: new RoundedRectangleBorder(
            borderRadius: new BorderRadius.circular(30.0)),
    )
    );
    return list;
}
@override
Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
            backgroundColor: Colors.purple,
            title: new Text("Home page"),
        ),
        body:
        Center(
            child:
            new Container(
                width: 500.0,
                height:300,
                color: Colors.white70,
                alignment: Alignment.center,
                child: new Column(
                    children:
                    makeRadios(),
                ),
            ),
        ),
    );
}

您已经有一个变量_selected,用于保存所选单选按钮的当前值。

void onPressed() {
    print('pressed $_selected');
}

它将打印当前选定的单选按钮值。

您可以将 print 语句替换为导航逻辑。

最新更新