在Flutter中,Radio
和RadioListTile
是用于创建单选按钮的组件。Radio
组件用于创建单个的单选按钮,而RadioListTile
是在ListTile
的基础上增加了单选功能的组件。
以下是使用Radio
和RadioListTile
的示例代码:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Interactive Components'),
),
body: Center(
child: RadioListExample(),
),
),
);
}
}
class RadioListExample extends StatefulWidget {
@override
_RadioListExampleState createState() => _RadioListExampleState();
}
class _RadioListExampleState extends State<RadioListExample> {
// 当前选中的Radio值
int groupValue = 0;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
RadioListTile(
title: Text('选项一'),
value: 0,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},
),
RadioListTile(
title: Text('选项二'),
value: 1,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},
),
RadioListTile(
title: Text('选项三'),
value: 2,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},
),
// 使用Radio组件创建单选按钮
Text('使用Radio组件:'),
Row(
children: <Widget>[
Radio(
value: 0,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},
),
Radio(
value: 1,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},
),
Radio(
value: 2,
groupValue: groupValue,
onChanged: (int value) {
setState(() {
groupValue = value;
});
},