Skip to content

Instantly share code, notes, and snippets.

@loic-sharma
Last active January 1, 2024 03:49
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 loic-sharma/da4365ce09e51fc5c48bba1779124ea2 to your computer and use it in GitHub Desktop.
Save loic-sharma/da4365ce09e51fc5c48bba1779124ea2 to your computer and use it in GitHub Desktop.
// Based off https://medium.com/akvelon/how-to-make-textfield-in-multiple-colors-in-flutter-c317ae0efafe
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
final controller = HubQLTextEditingController();
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Gradient Demo',
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Padding(
padding: const EdgeInsets.all(20),
child: TextField(
controller: controller,
style: const TextStyle(fontSize: 60),
),
),
),
);
}
}
class HubQLTextEditingController extends TextEditingController {
@override
TextSpan buildTextSpan({
required BuildContext context,
TextStyle? style,
required bool withComposing,
}) {
style ??= const TextStyle();
final TextStyle errorStyle = style.merge(const TextStyle(
decoration: TextDecoration.underline,
decorationColor: Colors.red,
decorationStyle: TextDecorationStyle.wavy,
));
final keywordStyle = style.copyWith(color: Colors.indigo);
final tokens = text.split(' ');
final children = <TextSpan>[];
for (var i = 0; i < tokens.length; i++) {
final token = tokens[i];
final TextStyle tokenStyle;
if (token == 'and') {
tokenStyle = keywordStyle;
} else if (token == 'or') {
tokenStyle = errorStyle;
} else {
tokenStyle = style;
}
children.add(
TextSpan(
text: token,
style: tokenStyle,
),
);
if (i < tokens.length - 1) {
children.add(
TextSpan(
text: ' ',
style: style,
),
);
}
}
return TextSpan(style: style, children: children);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment