Last active
January 1, 2024 03:49
-
-
Save loic-sharma/da4365ce09e51fc5c48bba1779124ea2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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