Sự phát triển của Flutter đang trở nên phổ biến và ngày càng phổ biến hơn do có nhiều tùy biến, widget tùy chỉnh và cách tiếp cận rất dễ thực hiện. Hôm nay chúng ta sẽ tìm hiểu cách tạo nút radio tùy chỉnh Flutter với các hình dạng tùy chỉnh như hộp đựng hình vuông, hộp đựng hình tròn hoặc biểu tượng. Tôi đã cố gắng tạo ra các phương pháp khác nhau để chúng có thể được sử dụng theo nhu cầu và nhà phát triển sẽ học từ hướng dẫn này cũng có thể có ý tưởng tạo nút radio tùy chỉnh rung của riêng mình, với hình dạng hoặc tiện ích theo yêu cầu của mình.

Ví dụ về Nút radio tùy chỉnh Flutter này sẽ tăng tốc độ phát triển của bạn và tiết kiệm thời gian của bạn bằng cách gọi nó trực tiếp như một phần tử con của bất kỳ tiện ích nào hoặc bằng cách thực hiện các phương thức tĩnh khi nó cần thiết. Bởi vì không có ứng dụng nào có thể được thực hiện mà không thực hiện bất kỳ widegt tùy chỉnh nào, tất cả các widget được tạo sẵn không phải lúc nào cũng giúp ích được. Vì vậy, học cách chế tạo widget tùy chỉnh là phần quan trọng nhất của quá trình phát triển Flagship.

Hãy bắt đầu thực hiện từng bước để chúng ta có thể hiểu những gì cần phải làm để đạt được kết quả đầu ra mong muốn. Đầu tiên, chúng ta sẽ tạo widget home, nơi chúng ta sẽ hiển thị các nút radio tùy chỉnh.

Nó là một widget toàn diện có khả năng xử lý tất cả các chức năng của nút radio, như hiển thị thiết kế tùy chỉnh, sự kiện chạm và lựa chọn, v.v.

home_screen.dart

class HomeScreen extends StatefulWidget {
  const HomeScreen({Key? key}) : super(key: key);
  @override
  _HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State {
  List radioOptions = [];
  @override
  void initState() {
    super.initState();
    radioOptions.add(RadioButtonModel(false, 'A', 'Option A'));
    radioOptions.add(RadioButtonModel(false, 'B', 'Option B'));
    radioOptions.add(RadioButtonModel(false, 'C', 'Option C'));
    radioOptions.add(RadioButtonModel(false, 'D', 'Option D'));
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Custom Check Box Example'),
      ),
      body: MyRadioButtonWidget(
        options: radioOptions,
        onItemSelected: (index) {
          print('I am index: $index');
        },
      ),
    );
  }
}

Giờ hãy tạo nút radio tùy chỉnh

Lớp này chịu trách nhiệm xử lý tất cả các hoạt động của nút radio tùy chỉnh, như thiết kế, sự kiện và gọi lại. Nếu bạn nhận thấy, tôi đã thêm một chức năng gọi lại để trả về chỉ mục mục được nhấn hiện tại. Trong trường hợp bạn muốn làm cho lớp nút radio tùy chỉnh của mình độc lập và chung chung, bạn có thể tạo cho các sự kiện theo yêu cầu của mình.

final Function(int)? onItemSelected;

my_radio_button_widget.dart

class MyRadioButtonWidget extends StatefulWidget {
  final List<RadioButtonModel>? options;
  final Function(int)? onItemSelected;
  const MyRadioButtonWidget({Key? key, this.options, this.onItemSelected})
      : super(key: key);
  @override
  createState() {
    return MyRadioButtonWidgetState();
  }
}
class MyRadioButtonWidgetState extends State<MyRadioButtonWidget> {
  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: widget.options!.length,
      itemBuilder: (BuildContext context, int index) {
        return InkWell(
          onTap: () {
            setState(() {
              for (var element in widget.options!) {
                element.isSelected = false;
              }
              widget.options![index].isSelected = true;
              widget.onItemSelected!(index);
            });
          },
          child: CircleRadioButtonItem(widget.options![index]),
        );
      },
    );
  }
}

Radio Button Model

class RadioButtonModel {
  bool isSelected;
  final String buttonText;
  final String text;
  RadioButtonModel(this.isSelected, this.buttonText, this.text);
}

Bây giờ chúng tôi sẽ tạo các hình dạng tùy chỉnh cho nút radio của chúng ta, ta có nhiều tùy chọn, bạn có thể tìm thấy ba lớp khác nhau để thể hiện phong cách khác nhau. bằng cách sử dụng ý tưởng này, bạn có thể tự tạo và sửa đổi các ví dụ đã cho theo ý muốn.

Nút radio vuông

Ở đây chúng tôi đang tạo hộp chứa hình vuông với văn bản bên trong nó.

class SquareRadioButtonItem extends StatelessWidget {
  final RadioButtonModel _item;
  const SquareRadioButtonItem(this._item, {Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(15.0),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            height: 50.0,
            width: 50.0,
            child: Center(
              child: Text(_item.buttonText,
                  style: TextStyle(
                      color: _item.isSelected ? Colors.white : Colors.black,
                      //fontWeight: FontWeight.bold,
                      fontSize: 18.0)),
            ),
            decoration: BoxDecoration(
              color: _item.isSelected ? Colors.blueAccent : Colors.transparent,
              border: Border.all(
                  width: 1.0,
                  color: _item.isSelected ? Colors.blueAccent : Colors.grey),
              borderRadius: const BorderRadius.all(Radius.circular(2.0)),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 10.0),
            child: Text(_item.text),
          )
        ],
      ),
    );
  }
}

Nút radio tròn

class CircleRadioButtonItem extends StatelessWidget {
  final RadioButtonModel _item;
  const CircleRadioButtonItem(this._item, {Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(15.0),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          Container(
            height: 50.0,
            width: 50.0,
            child: Center(
              child: Text(_item.buttonText,
                  style: TextStyle(
                      color: _item.isSelected ? Colors.white : Colors.black,
                      //fontWeight: FontWeight.bold,
                      fontSize: 18.0)),
            ),
            decoration: BoxDecoration(
              shape: BoxShape.circle,
              color: _item.isSelected ? Colors.blueAccent : Colors.transparent,
              border: Border.all(
                  width: 1.0,
                  color: _item.isSelected ? Colors.blueAccent : Colors.grey),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(left: 10.0),
            child: Text(_item.text),
          )
        ],
      ),
    );
  }
}

Icon Radio

class IconRadioButtonItem extends StatelessWidget {
  final RadioButtonModel _item;
  const IconRadioButtonItem(this._item, {Key? key}) : super(key: key);
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: const EdgeInsets.all(15.0),
      child: Row(
        mainAxisSize: MainAxisSize.max,
        children: [
          _item.isSelected
              ? const Icon(Icons.circle)
              : const Icon(Icons.circle_outlined),
          Container(
            margin: const EdgeInsets.only(left: 10.0),
            child: Text(_item.text),
          )
        ],
      ),
    );
  }
}

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.

You may also like