Skip to content

Instantly share code, notes, and snippets.

@heemoe
Created December 7, 2021 18:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heemoe/6677de951736b457bd862890e3aeb834 to your computer and use it in GitHub Desktop.
Save heemoe/6677de951736b457bd862890e3aeb834 to your computer and use it in GitHub Desktop.
flutter custom text switch controller
import 'package:flutter/material.dart';
class CustomSwitch extends StatefulWidget {
const CustomSwitch(
{Key? key, required this.leftStr, required this.rightStr, this.onChange})
: super(key: key);
final String leftStr;
final String rightStr;
final Function(int selected)? onChange;
@override
State<StatefulWidget> createState() {
return _CustomSwitch();
}
}
class _CustomSwitch extends State<CustomSwitch> {
final TextStyle _textStyle =
const TextStyle(fontSize: 10, color: Colors.white);
var selected = 0;
void onItemSelected(int idx) {
setState(() {
selected = idx;
});
if (widget.onChange != null) {
widget.onChange?.call(idx);
}
}
@override
Widget build(BuildContext context) {
return Container(
decoration: const BoxDecoration(
color: Color(0xff5E3BF5),
borderRadius: BorderRadius.all(Radius.circular(60))),
child: SizedBox(
width: 60,
height: 18,
child: Row(
children: [
_buildItem(
widget.leftStr, selected == 0, () => onItemSelected(0)),
_buildItem(
widget.rightStr, selected == 1, () => onItemSelected(1)),
],
)),
);
}
_buildItem(String text, bool isSelected, GestureTapCallback cb) {
return Expanded(
flex: 1,
child: InkWell(
onTap: cb,
child: Container(
height: 27,
alignment: Alignment.center,
decoration: BoxDecoration(
borderRadius: const BorderRadius.all(Radius.circular(20)),
color: isSelected
? const Color(0xff9279FE)
: const Color(0x000000ff)),
child: Text(
text,
style: _textStyle,
),
),
));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment