Flutter自定义分组单选按钮插件custom_radio_grouped_button的使用

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

Flutter自定义分组单选按钮插件custom_radio_grouped_button的使用

custom_radio_grouped_button 是一个用于创建自定义样式单选按钮和分组复选框的Flutter插件。它使Checkbox和Radio Buttons更加简洁易用。

安装

在您的 pubspec.yaml 文件中添加以下依赖:

dependencies:
  custom_radio_grouped_button: any

然后执行 flutter pub get 来安装该包。

创建RadioButton

下面是如何创建一个自定义的RadioButton的例子:

CustomRadioButton(
  elevation: 0,
  absoluteZeroSpacing: true,
  unSelectedColor: Theme.of(context).canvasColor,
  buttonLables: [
    'Student',
    'Parent',
    'Teacher',
  ],
  buttonValues: [
    "STUDENT",
    "PARENT",
    "TEACHER",
  ],
  buttonTextStyle: ButtonTextStyle(
      selectedColor: Colors.white,
      unSelectedColor: Colors.black,
      textStyle: TextStyle(fontSize: 16)),
  radioButtonValue: (value) {
    print(value);
  },
  selectedColor: Theme.of(context).accentColor,
),

创建GroupedButton

创建一个分组按钮也很简单,下面是一个例子:

CustomCheckBoxGroup(
  buttonTextStyle: ButtonTextStyle(
    selectedColor: Colors.red,
    unSelectedColor: Colors.orange,
    textStyle: TextStyle(
      fontSize: 16,
    ),
    selectedTextStyle: TextStyle(
      fontSize: 20,
      fontWeight: FontWeight.w700,
    ),
  ),
  unSelectedColor: Theme.of(context).canvasColor,
  buttonLables: [
    "M",
    "T",
    "W",
    "T",
    "F",
    "S",
    "S",
  ],
  buttonValuesList: [
    "Monday",
    "Tuesday",
    "Wednesday",
    "Thursday",
    "Friday",
    "Saturday",
    "Sunday",
  ],
  checkBoxButtonValues: (values) {
    print(values);
  },
  spacing: 0,
  defaultSelected: "Monday",
  horizontal: false,
  enableButtonWrap: false,
  width: 40,
  absoluteZeroSpacing: false,
  selectedColor: Theme.of(context).accentColor,
  padding: 10, 
);

程序化改变值

你可以通过 Key 访问widget的状态来程序化地改变值。

例如,为 CustomRadioButton widget创建一个key:

final key = new GlobalKey<CustomRadioButtonState<T>>();

要改变widget的值,可以调用 selectButton 方法:

key.currentState.selectButton(<value>);

对于 CustomCheckBoxGroup widget也是类似的:

final key = new GlobalKey<CustomCheckBoxGroupState<T>>();

key.currentState.selectButton(<value>);

示例Demo

以下是一个完整的示例demo,包含了如何使用这个插件:

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

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

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

class GroupedButton extends StatelessWidget {
  const GroupedButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Grouped Button Example'),
        centerTitle: true,
      ),
      floatingActionButton: FloatingActionButton.extended(
        label: Text('Radio Button'),
        onPressed: () {
          Navigator.push(
              context, MaterialPageRoute(builder: (context) => RadioButton()));
        },
        icon: Icon(Icons.radio_button_checked),
      ),
      body: Container(
        child: ListView(
          children: <Widget>[
            SizedBox(
              height: 10,
            ),
            Text(
              'Horizontal',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Row(
              children: <Widget>[
                Expanded(
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Shape Disabled',
                        style: TextStyle(fontSize: 15),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      CustomCheckBoxGroup<String>(
                        unSelectedColor: Theme.of(context).canvasColor,
                        buttonLables: [
                          "Monday",
                          "Tuesday",
                          "Wednesday",
                          "Thursday",
                        ],
                        disabledValues: [
                          "Monday",
                        ],
                        buttonValuesList: [
                          "Monday",
                          "Tuesday",
                          "Wednesday",
                          "Thursday",
                        ],
                        checkBoxButtonValues: (values) {
                          print(values);
                        },
                        defaultSelected: ["Monday"],
                        horizontal: true,
                        width: 120,
                        selectedColor: Theme.of(context).colorScheme.secondary,
                        padding: 5,
                        spacing: 0.0,
                      ),
                    ],
                  ),
                ),
                Expanded(
                  child: Column(
                    children: <Widget>[
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Shape Enabled',
                        style: TextStyle(fontSize: 15),
                      ),
                      SizedBox(
                        height: 10,
                      ),
                      CustomCheckBoxGroup(
                        unSelectedColor: Theme.of(context).canvasColor,
                        buttonLables: [
                          "Thursday Thursday Thursday Thursday",
                          "Friday",
                          "Saturday",
                          "Sunday",
                        ],
                        buttonValuesList: [
                          "Thursday",
                          "Friday",
                          "Saturday",
                          "Sunday",
                        ],
                        checkBoxButtonValues: (values) {
                          print(values);
                        },
                        defaultSelected: ["Sunday"],
                        horizontal: true,
                        width: 120,
                        selectedColor: Theme.of(context).colorScheme.secondary,
                        padding: 5,
                        enableShape: true,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            SizedBox(
              height: 10,
            ),
            Text(
              'Verticle',
              textAlign: TextAlign.center,
              style: TextStyle(fontSize: 20),
            ),
            SizedBox(
              height: 10,
            ),
            Column(
              children: <Widget>[
                Column(
                  children: <Widget>[
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      'Shape Disabled',
                      style: TextStyle(fontSize: 15),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CustomCheckBoxGroup(
                      buttonTextStyle: ButtonTextStyle(
                        selectedColor: Colors.pinkAccent,
                        unSelectedColor: Colors.orange,
                        textStyle: TextStyle(
                          fontSize: 16,
                        ),
                        selectedTextStyle: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.w700,
                        ),
                      ),
                      unSelectedColor: Theme.of(context).canvasColor,
                      buttonLables: [
                        "M",
                        "T",
                        "W",
                        "T",
                        "F",
                        "S",
                        "S",
                      ],
                      disabledValues: [
                        "Monday",
                      ],
                      buttonValuesList: [
                        "Monday",
                        "Tuesday",
                        "Wednesday",
                        "Thursday",
                        "Friday",
                        "Saturday",
                        "Sunday",
                      ],
                      checkBoxButtonValues: (values) {
                        print(values);
                      },
                      spacing: 0,
                      defaultSelected: ["Monday"],
                      horizontal: false,
                      enableButtonWrap: false,
                      width: 40,
                      selectedColor: Theme.of(context).colorScheme.secondary,
                      padding: 10,
                    ),
                  ],
                ),
                Column(
                  children: <Widget>[
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      'Shape Enabled and Wrap enabled',
                      style: TextStyle(fontSize: 15),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    CustomCheckBoxGroup(
                      buttonTextStyle: ButtonTextStyle(
                        selectedColor: Colors.white,
                        unSelectedColor: Colors.black,
                        textStyle: TextStyle(
                          fontSize: 16,
                        ),
                      ),
                      autoWidth: false,
                      enableButtonWrap: true,
                      wrapAlignment: WrapAlignment.center,
                      unSelectedColor: Theme.of(context).canvasColor,
                      buttonLables: [
                        "Monday Monday Mondays",
                        "Tuesday",
                        "Wednesday",
                        "Thursday",
                        "Friday",
                        "Saturday",
                        "Sunday",
                      ],
                      buttonValuesList: [
                        "Monday",
                        "Tuesday",
                        "Wednesday",
                        "Thursday",
                        "Friday",
                        "Saturday",
                        "Sunday",
                      ],
                      checkBoxButtonValues: (values) {
                        print(values);
                      },
                      defaultSelected: ["Sunday"],
                      horizontal: false,
                      width: 120,
                      selectedColor: Theme.of(context).colorScheme.secondary,
                      padding: 5,
                      enableShape: true,
                    ),
                  ],
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

以上就是 custom_radio_grouped_button 插件的详细使用方法和一个完整的示例demo。希望对您有所帮助!


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

1 回复

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


当然,以下是一个关于如何在Flutter中使用custom_radio_grouped_button插件来实现自定义分组单选按钮的示例代码。首先,你需要确保已经将该插件添加到你的Flutter项目中。

添加依赖

在你的pubspec.yaml文件中添加以下依赖:

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

然后运行flutter pub get来安装依赖。

示例代码

下面是一个完整的示例代码,展示了如何使用custom_radio_grouped_button插件:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Custom Radio Grouped Button Example'),
        ),
        body: Center(
          child: RadioGroupedButtonExample(),
        ),
      ),
    );
  }
}

class RadioGroupedButtonExample extends StatefulWidget {
  @override
  _RadioGroupedButtonExampleState createState() => _RadioGroupedButtonExampleState();
}

class _RadioGroupedButtonExampleState extends State<RadioGroupedButtonExample> {
  String selectedValue = '';

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Text(
          'Selected Value: $selectedValue',
          style: TextStyle(fontSize: 20),
        ),
        SizedBox(height: 20),
        CustomRadioGroupedButton(
          groupValue: selectedValue,
          onChanged: (value) {
            setState(() {
              selectedValue = value;
            });
          },
          buttons: [
            CustomRadioGroupedButtonModel(
              label: 'Option 1',
              value: 'option1',
              icon: Icons.radio_button_unchecked,
              selectedIcon: Icons.radio_button_checked,
            ),
            CustomRadioGroupedButtonModel(
              label: 'Option 2',
              value: 'option2',
              icon: Icons.radio_button_unchecked,
              selectedIcon: Icons.radio_button_checked,
            ),
            CustomRadioGroupedButtonModel(
              label: 'Option 3',
              value: 'option3',
              icon: Icons.radio_button_unchecked,
              selectedIcon: Icons.radio_button_checked,
            ),
          ],
          orientation: Axis.horizontal,  // 可以是 Axis.vertical 或 Axis.horizontal
          buttonPadding: EdgeInsets.all(8.0),
          buttonStyle: TextStyle(fontSize: 16),
          labelStyle: TextStyle(fontSize: 16),
        ),
      ],
    );
  }
}

解释

  1. 依赖添加:在pubspec.yaml文件中添加custom_radio_grouped_button依赖。
  2. 创建UI:在RadioGroupedButtonExample组件中,我们定义了一个selectedValue来存储选中的值。
  3. CustomRadioGroupedButton
    • groupValue:当前选中的值。
    • onChanged:当选中值改变时的回调函数。
    • buttons:按钮数组,每个按钮包含labelvalueiconselectedIcon等属性。
    • orientation:按钮的排列方向,可以是水平(Axis.horizontal)或垂直(Axis.vertical)。
    • buttonPadding:按钮的内边距。
    • buttonStyle:按钮文本的样式。
    • labelStyle:标签文本的样式。

这个示例展示了如何使用custom_radio_grouped_button插件来创建一个自定义分组单选按钮,并处理选中值的变化。你可以根据需求进一步自定义按钮的样式和行为。

回到顶部