Flutter单选组件插件flutter_radio_group的使用

发布于 1周前 作者 htzhanglong 来自 Flutter

Flutter单选组件插件flutter_radio_group的使用

flutter_radio_group 是一个用于Flutter的简单且美观的单选组控件,支持自定义标签、标题、标签样式、标题样式、方向等,并能维护 onChanged 状态。

Getting Started

首先,在您的Flutter项目的 pubspec.yaml 文件中添加依赖:

dependencies:
  flutter_radio_group: "^latest_version"

然后导入包:

import 'package:flutter_radio_group/flutter_radio_group.dart';

确保替换 "^latest_version" 为实际的最新版本号。

Demo

Demo GIF

使用示例

下面是一个简单的例子,展示了如何创建水平排列的单选按钮组:

var _listHorizontal = ["Horizontal 1", "Horizontal 2", "Horizontal 3"];
var _indexHorizontal = 0;

FlutterRadioGroup(
    titles: _listHorizontal,
    labelStyle: TextStyle(color: Colors.white38),
    labelVisible: true,
    label: "This is label radio",
    activeColor: Colors.blue,
    titleStyle: TextStyle(fontSize: 14),
    defaultSelected: _indexHorizontal,
    orientation: RGOrientation.HORIZONTAL,
    onChanged: (index) {
      setState(() {
        _indexHorizontal = index;
      });
    }),

编程选择索引

如果您需要编程方式更改选中的索引,可以使用 GlobalKey:

var _key = GlobalKey<RadioGroupState>();

/// 更新选中的单选按钮
_key.currentState.setIndexSelected(3);

FlutterRadioGroup(
    key: _key,
    titles: _listHorizontal,
    labelStyle: TextStyle(color: Colors.white38),
    labelVisible: true,
    label: "This is label radio",
    activeColor: Colors.blue,
    titleStyle: TextStyle(fontSize: 14),
    defaultSelected: _indexHorizontal,
    orientation: RGOrientation.HORIZONTAL,
    onChanged: (index) {
      setState(() {
        _listHorizontal = index;
      });
    }),

完整示例代码

这里提供了一个更完整的示例代码,包括垂直和水平布局的单选按钮组:

import 'package:flutter/material.dart';
import 'package:flutter_radio_group/flutter_radio_group.dart';

void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  [@override](/user/override)
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  var _listHorizontal = ["Horizontal 1", "Horizontal 2", "Horizontal 3"];
  var _listVertical = ["Vertical 1", "Vertical 2", "Vertical 3"];

  var _keyVertical = GlobalKey<FlutterRadioGroupState>();
  var _keyHorizontal = GlobalKey<FlutterRadioGroupState>();

  var _indexHorizontal = 0;
  var _indexVertical = 1;

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text('Plugin example app')),
        body: SingleChildScrollView(
          child: Padding(
            padding: EdgeInsets.all(16.0),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: <Widget>[
                Text(
                  "Vertical -> index selected $_indexVertical - ${_listVertical[_indexVertical]}",
                  style: TextStyle(fontSize: 16),
                ),
                FlutterRadioGroup(
                    key: _keyVertical,
                    titles: _listVertical,
                    defaultSelected: _indexVertical,
                    onChanged: (index) {
                      setState(() {
                        _indexVertical = index;
                      });
                    }),
                ElevatedButton(
                    onPressed: () {
                      _keyVertical.currentState.setIndexSelected(2);
                      setState(() {
                        _indexVertical = 2;
                      });
                    },
                    child: Text("Select index 2")),
                Divider(height: 32),
                Text(
                  "Horizontal -> index selected $_indexHorizontal - ${_listHorizontal[_indexHorizontal]}",
                  style: TextStyle(fontSize: 16),
                ),
                SizedBox(height: 16),
                FlutterRadioGroup(
                    key: _keyHorizontal,
                    titles: _listHorizontal,
                    labelStyle: TextStyle(color: Colors.pink),
                    defaultSelected: _indexHorizontal,
                    label: "Label Horizontal",
                    orientation: RGOrientation.HORIZONTAL,
                    onChanged: (index) {
                      setState(() {
                        _indexHorizontal = index;
                      });
                    }),
                ElevatedButton(
                    style: ButtonStyle(
                      backgroundColor: MaterialStateProperty.all(Colors.amber)
                    ),
                    onPressed: () {
                      _keyHorizontal.currentState.setIndexSelected(1);
                      setState(() {
                        _indexHorizontal = 1;
                      });
                    },
                    child: Text("Select index 1")),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

更多关于Flutter单选组件插件flutter_radio_group的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter单选组件插件flutter_radio_group的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,flutter_radio_group 是一个用于在 Flutter 中创建单选按钮组的插件。它提供了方便的方法来管理一组单选按钮,并确保只有一个按钮可以被选中。下面是一个简单的示例代码,展示如何使用 flutter_radio_group 插件。

首先,确保你已经在 pubspec.yaml 文件中添加了 flutter_radio_group 依赖:

dependencies:
  flutter:
    sdk: flutter
  flutter_radio_group: ^latest_version  # 请替换为最新版本号

然后,运行 flutter pub get 来获取依赖。

接下来,在你的 Dart 文件中,你可以按照以下方式使用 flutter_radio_group

import 'package:flutter/material.dart';
import 'package:flutter_radio_group/flutter_radio_group.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Radio Group Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  String? selectedValue;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter Radio Group Demo'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RadioGroup<String>(
              label: Text('Choose an option:'),
              onChanged: (value) {
                setState(() {
                  selectedValue = value;
                });
              },
              options: [
                RadioGroupOption<String>(
                  value: 'Option 1',
                  title: Text('Option 1'),
                ),
                RadioGroupOption<String>(
                  value: 'Option 2',
                  title: Text('Option 2'),
                ),
                RadioGroupOption<String>(
                  value: 'Option 3',
                  title: Text('Option 3'),
                ),
              ],
            ),
            SizedBox(height: 20),
            Text('Selected Value: $selectedValue'),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的 Flutter 应用,其中包含一个 RadioGroup 组件。RadioGroup 接受一个 label 参数,用于显示单选按钮组的标签,以及一个 onChanged 回调,当选中项发生变化时会调用该回调。options 参数是一个 RadioGroupOption 列表,每个选项都有一个 value 和一个 title

当用户选择一个选项时,onChanged 回调会被触发,并更新 selectedValue 状态。然后,我们在界面上显示当前选中的值。

这样,你就可以使用 flutter_radio_group 插件来创建和管理单选按钮组了。

回到顶部