直接上代码,利用回调方法获取内部事件的值
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; typedef void OnRaidoChange(String val); // 声明一个方法 class RadioSelect extends StatefulWidget { final List<String> items; final OnRaidoChange onValueChangedCallBack; // 用于回调,主要就是使用这个方法获取内部的值 RadioSelect( {GlobalKey<_RadioSelectState> key, // GlobalKey @required this.items, this.onValueChangedCallBack}) : super(key: key); GlobalKey<_RadioSelectState> getKey() { return this.key; } @override _RadioSelectState createState() { return new _RadioSelectState(); } } class _RadioSelectState extends State<RadioSelect> { List<Widget> itemWidget = new List(); // 通过Wiget列表方式给Children赋值 String value; @override void initState() { if (widget.items == null) { throw new Exception( '<RadioSelect> attribute ``items`` must not be null.'); } for (int i = 0; i < widget.items.length; i++) { itemWidget.add( Container( child: GestureDetector( child: Row( children: <Widget>[ Container( child: Icon(Icons.check_circle), ), Container( child: Text(widget.items[i]), ) ], ), onTap: () { setState(() { this.value = widget.items[i]; // 点击赋值 }); if (widget.onValueChangedCallBack != null) { widget.onValueChangedCallBack(widget.items[i]); // 把值传给方法,谁调谁知道 } }, ), ), ); } } @override Widget build(BuildContext context) { return Container( child: Wrap( children: itemWidget, ), ); } }
使用:
var items = ['1', '2']; return Row( children: <Widget>[ RadioSelect( items: items, onValueChangedCallBack: (val) { _radioValue = val; }, ), FlatButton( child: Text('点我'), onPressed: () { print(_radioValue); }, ), ], );