ToggleButton in flutter





 import 'package:flutter/material.dart';


class ToggleButton extends StatefulWidget {
  final String firstText;
  final String secondText;
  final ValueChanged<int>? onToggle;

  ToggleButton({
    required this.firstText,
    required this.secondText,
    this.onToggle,
  });

  @override
  _ToggleButtonState createState() => _ToggleButtonState();
}

class _ToggleButtonState extends State<ToggleButton> {
  int _selected = 0;

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        _buildButton(0, widget.firstText),
        _buildButton(1, widget.secondText),
      ],
    );
  }

  Widget _buildButton(int index, String text) {
    bool isSelected = _selected == index;

    return Container(
      margin: EdgeInsets.symmetric(horizontal: 4.0),
      child: OutlinedButton(
        onPressed: () {
          setState(() {
            _selected = index;
            if (widget.onToggle != null) {
              widget.onToggle!(_selected);
            }
          });
        },
        style: ButtonStyle(
          side: MaterialStateProperty.all(
            BorderSide(
              color: isSelected ? Colors.blue : Colors.grey,
              width: 1.0,
            ),
          ),
          shape: MaterialStateProperty.all(
            RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(8.0),
            ),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: isSelected ? Colors.blue : Colors.grey,
          ),
        ),
      ),
    );
  }
}

Comments