
在日常的开发中,我们可能会遇到以下需求:
多个选项,实现按钮的单选。
这篇博客,我们来分享Flutter
怎么实现这种需求。希望对看文章的小伙伴有帮助。
简单的示例代码
enum RadioValue { android, iOS, flutter }
RadioValue _radioValue = RadioValue.flutter;
Radio<RadioValue>(
value: RadioValue.android,
groupValue: _radioValue,
onChanged: (value) {
// 更新_radioValue
setState(() {
_radioValue = value!;
});
}),
const Text(
'android',
style: TextStyle(fontSize: 18.0),
),
上面是单个按钮的使用,多个按钮使用效果如下图:

属性说明
当前按钮的值:
value: RadioValue.android,
当前的选中是哪个一个:
groupValue: _radioValue,
点击事件的回调:
onChanged: (value) {
// 更新_radioValue
setState(() {
_radioValue = value!;
});
}
选中效果的颜色修改:
activeColor:Colors.blue,
完整的代码
以下的代码,可以直接复制到编译器去运行,方便小伙伴查看运行结果或者直接使用:
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
enum RadioValue { android, iOS, flutter }
class _MyHomePageState extends State<MyHomePage> {
RadioValue _radioValue = RadioValue.flutter;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
child: Row(
children: <Widget>[
Radio<RadioValue>(
value: RadioValue.android,
groupValue: _radioValue,
onChanged: (value) {
// 更新_radioValue
setState(() {
_radioValue = value!;
});
}),
const Text(
'android',
style: TextStyle(fontSize: 18.0),
),
Radio<RadioValue>(
value: RadioValue.iOS,
groupValue: _radioValue,
onChanged: (value) {
// 更新_radioValue
setState(() {
_radioValue = value!;
});
}),
const Text(
'iOS',
style: TextStyle(fontSize: 18.0),
),
Radio<RadioValue>(
value: RadioValue.flutter,
groupValue: _radioValue,
onChanged: (value) {
// 更新_radioValue
setState(() {
_radioValue = value!;
});
}),
const Text(
'Flutter',
style: TextStyle(fontSize: 18.0),
),
],
),
),
);
}
}
网友评论