Created
December 9, 2019 18:09
-
-
Save mingsai/a4a3a1bda6544760963cc27bb02e8042 to your computer and use it in GitHub Desktop.
Clickable TextSpan Behavior (Change text on tap)
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
import 'package:flutter/material.dart'; | |
import 'package:flutter/gestures.dart'; | |
class MakeStringClickable extends StatefulWidget { | |
@override | |
State<StatefulWidget> createState() { | |
return _MakeStringClickableState(); | |
} | |
} | |
class _MakeStringClickableState extends State<MakeStringClickable> { | |
List<TapSection> sections; | |
String textToSplit = | |
'FirstWord would like to make each word clickable. On click of a particular word it\'s color should change.'; | |
TapGestureRecognizer r1; | |
@override | |
void initState() { | |
sections = List<TapSection>(); | |
super.initState(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Container( | |
alignment: Alignment.center, | |
child: _buildTextSpanWithSplittedText(textToSplit, context)); | |
} | |
RichText _buildTextSpanWithSplittedText( | |
String textToSplit, BuildContext context) { | |
final splittedText = textToSplit.split(" "); | |
final spans = List<TextSpan>(); | |
for (int i = 0; i <= splittedText.length - 1; i++) { | |
var tapSection = TapSection(callBack: () { | |
setState(() {}); | |
}); | |
sections.add(tapSection); | |
spans.add(TextSpan( | |
text: splittedText[i].toString() + " ", | |
style: TextStyle( | |
color: sections[i].isPressed ? Colors.black : Colors.red), | |
recognizer: sections[i].recognizer)); | |
} | |
return RichText(text: TextSpan(children: spans)); | |
} | |
} | |
class TapSection { | |
TapGestureRecognizer recognizer; | |
bool isPressed = false; | |
final Function callBack; | |
TapSection({this.callBack}) { | |
recognizer = TapGestureRecognizer(); | |
recognizer.onTap = () { | |
this.isPressed = !this.isPressed; | |
this.callBack(); | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment