How to use new line character in Text Widget Flutter - flutter

How to display multiline text in Flutter?
Text("Text1\n Text2\n Text3",maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )

Approach 1 Using Triple quotes
child: Container(
child : Text('''
Text1
Text2
Text3''',maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )
),
Approach 2 Using \n here is example with Dynamic String :
var readLines = ['Test1', 'Test2', 'Test3'];
String getNewLineString() {
StringBuffer sb = new StringBuffer();
for (String line in readLines) {
sb.write(line + "\n");
}
return sb.toString();
}
child: Container(
child: Text(
getNewLineString(),
maxLines: 20,
style: TextStyle(
fontSize: 16.0,
fontWeight: FontWeight.bold,
color: Colors.black),
)),
Approach 3 using static text with \n
Text('Welcome\nto\nMyWorld\nHello\nWorld\n');
For more, you should refer to this link
https://api.dartlang.org/stable/2.5.0/dart-core/String-class.html

For me, when getting data with '\n' in the text from the local sqlite database, this worked:
var message = await db.getDataFromDB();
return Text(message.replaceAll('\\n', '\n'))

If you want to break line with a string that comes from outside the Flutter you should modify the string inside flutter.
So if you get from API a string 'Order received! \n Wait in the line!' and the break line is not working, in flutter you should replace the '\n' inside flutter
var response = await getMessageFromServer();
String message = getMessage(response);
return Text(message.replaceAll('\n', '\n'))
This way you will see how the color of '\n' is different in flutter.
I prefered using '/n' for the API and then in flutter I replace.all('/n', '\n')

One other option I found is to use a RichText widget as follows:
RichText(
text: TextSpan(
text: 'A line with a newline character\n',
children: [
TextSpan(
text: 'A second line',
),
],
),
),

Just use this
Text('${userInfo.name}'
'\n${userInfo.email}'
'\n${userInfo.mobilenumber}',maxLines: 20, style: TextStyle(fontSize: 16.0 ,fontWeight:FontWeight.bold,color: Colors.black) , )

You can write multiple lines of text in the Text() widget by simply enclose every line of text with a separate quote(" ").
Like this, look at the screenshot.

Related

What is the correct way to trim a string to a certain amount of characters after a certain character?

I am attempting to trim a string that is a number (ex. "123456.1234"). I want to trim it to only have two characters after the decimal (ex. "123456.12"). I've been trying this with substring but to no avail. What is the right way to do this? Thanks!
Example of what I'm working with where the_number_string is the string that needs trimmed.
Container(
margin: EdgeInsets.all(10),
child: Text(
'\$${data.the_number_string}',
style: TextStyle(
color: Colors.black, fontSize: 15),
),
)
Since you insist on a String solution. First find the index of "." and then use substring. Please see the code below.
void main() {
String abc = "123456.1234";
print(abc.substring(0,abc.indexOf(".")+3));
}
This will work, though you should consider using double for such cases:
Container(
margin: EdgeInsets.all(10),
child: Text(
'\$${num.tryParse(data.the_number_string).toStringAsFixed(2)}',
style: TextStyle(
color: Colors.black, fontSize: 15),
),
)

Formatting text in flutter

I am styling text but am not able to get what I want like -:
I want this text below
look like this -:
how do I do it can anyone help?
If you want each word on a new line
String text = "Lorem ipsum dolor sit amet";
Text(
text.replaceAll(" ", "\n"),
),
text.replaceAll(" ", "\n") will replace all space with \n(new line)
You can use \n (optn + shift + 7) to make a new line inside you're String.
Container(
child: Center(
child: Text('Hello \nWorld',
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22.0,
fontWeight: FontWeight.bold,
letterSpacing: 0.7
)
),
),
),
Use textAlign to make your text align in the center (default is align left).
Its seem like by your comment you have a dynamic data. Since your question is not very clear, I will give you sample example to handle dynamic Data.
List a = ['Hello World', 'Hello', 'World'];
ListView(
children: a.map((e) {
if (e == "Hello") {
return Text(
e,
textAlign: TextAlign.end,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
);
} else if (e == "World") {
return Text(
e,
textAlign: TextAlign.end,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
);
} else {
return Text(
e,
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
);
}
}).toList()),
Code Explanation
1). I have declare a Random List of String.
2). Then I used List View to handle dynamic list.
3). I put iteration and use a Text widget and put some style according to my Requirment.
you can put condition by yourself what you needed.
You can use \n to make a new line
Code:
Center(
child: Text('Hello Guys, Thanks \nfor visiting our website \nFlutter Examples.com',
style: TextStyle(fontSize: 22),
textAlign: TextAlign.center)
)

Changing text color if text contains hashtag "#"

Basically I want to achieve a "hashtag" feature.
I'm having a hard time making a logic wherein if the text contains a "#" (eg. I love #flutter), the #flutter text will change its color to blue.
Can you give me a hint on what widget to use or is there a package for this?
I can't seem to find a similar problem.
hope this works!
Widget _getColoredHashtagText(String text) {
if (text.contains('#')) {
var preHashtag = text.substring(0, text.indexOf('#'));
var postHashtag = text.substring(text.indexOf('#'));
var hashTag = postHashtag;
var other;
if (postHashtag.contains(' ')) {
hashTag = postHashtag.substring(0, postHashtag.indexOf(' '));
other = postHashtag.substring(postHashtag.indexOf(' '));
}
return RichText(
text: TextSpan(
style: DefaultTextStyle.of(context).style,
children: <TextSpan>[
TextSpan(text: preHashtag),
TextSpan(text: hashTag, style: TextStyle(color: Colors.blue)),
TextSpan(text: other != null ? other : ""),
],
),
);
} else {
return Text(text);
}
}
With RichText you can create a text with different styles, where each text is a TextSpan, like this:
RichText(
text: TextSpan(
children: [
TextSpan(text: "I love "),
TextSpan(text: "#flutter", style: TextStyle(color: Colors.blue)),
],
),
)
You could take a String and create a list of texts and hashtags, then map that list checking: if the element contains # then use a TextSpan with color blue, otherwise use a default TextSpan.
Here is a quick working example, you could try to improve it:
RichText _convertHashtag(String text) {
List<String> split = text.split(RegExp("#"));
List<String> hashtags = split.getRange(1, split.length).fold([], (t, e) {
var texts = e.split(" ");
if (texts.length > 1) {
return List.from(t)
..addAll(["#${texts.first}", "${e.substring(texts.first.length)}"]);
}
return List.from(t)..add("#${texts.first}");
});
return RichText(
text: TextSpan(
children: [TextSpan(text: split.first)]..addAll(hashtags
.map((text) => text.contains("#")
? TextSpan(text: text, style: TextStyle(color: Colors.blue))
: TextSpan(text: text))
.toList()),
),
);
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.indigo,
appBar: AppBar(title: Text('#hashtag')),
body: Center(
child: _convertHashtag("I love #flutter and #android very much"),
),
);
}
HashTagText
https://pub.dev/packages/hashtagtext#-installing-tab-
I published this library. It will auto detect hash tags from string and make highlighted.
dependencies:
hashtagtext: ^0.0.1
EXAMPLE
HashTagText(text: "I will found and #highlight all #tag and #make it #clickable", onHashTagClick: (tag){
print("You clicked on $tag");
},)

More GestureRecognisers For The TextSpan In Flutter

I building an application in Flutter and I am in a situation where I got RichText widget with many TextSpan widgets and I need to have two gesture recognizers, one is on double tap and the other is on long press, so how do I do this if it is possible?
Can't you just wrap the entire Text Span in the gesture detector widget? https://api.flutter.dev/flutter/widgets/GestureDetector-class.html
Each textSpan comes with its own text and children property for which you can use the recognizer property and implement different taps as needed.
Consider below example:
Container(
color: Colors.black,
padding: EdgeInsets.all(10),
child: Center(
child: RichText(
text: TextSpan( // <-- 1
text: 'This is a text from first textspan. ',
style: TextStyle(
color: Colors.grey,
fontSize: 20,
fontWeight: FontWeight.bold),
children: <TextSpan>[ // <-- 2
TextSpan(
text: ' This is a text from second textspan ',
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold),
recognizer: LongPressGestureRecognizer()
..onLongPress = () {
print('Long pressed');
},
children: <
TextSpan>[ // <-- 3 (children of 2 textspan
TextSpan(
text: ' This is a another text from second textspan',
recognizer: DoubleTapGestureRecognizer()
..onDoubleTap = () {
print('double tapped');
}
)
]
),
]
),
)
)
)
The children: <TextSpan>[] commented as 2 has a text property and corresponding recognizer in which I used LongPressGestureRecognizer(). The same textSpan (2), has children property which again can have a sub text span with a text and corresponding recognizer in which I used DoubleTapGestureRecognizer().
So the output will be : You can long press on This is a text from second textspan and you can double tap on This is another text from second textspan.
Hope this answers your question.

How can I change the color of several words in the TextField Widget?

Im trying to do chat mentions and I need to some how change the color of full name that mentioned in the TextField before send the message.
How can I do that?
Hope i'm not too late :)
I had the same issue and couldn't find any implementation in the main flutter package or any third party packages, so i hacked a little packaage and uploaded it.
it's an extension of the text editing controller that you can supply with a map of Regex patterns and corresponding Text style.
https://pub.dev/packages/rich_text_controller
https://github.com/micwaziz/rich_text_controller
In case someone stumbles across this question (like I did) but requires the textfield to render tap-able links, then here's one way to do it (simplified from our final implementation for better clarity). It's inspired by the RichTextController, but with the definitive focus to allow for taps on the links.
Regarding the regular expression: We tried using linkify, but despite trying all options, it tended to modify the links - which messed up the user input.
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:url_launcher/url_launcher.dart';
class LinkedTextEditingController extends TextEditingController {
final RegExp linkRegexp;
final TextStyle linkStyle;
final Function(String match) onTap;
static RegExp _defaultRegExp =
RegExp(r'((?:(https?:\/\/)?)(www\.)?[-a-zA-Z0-9#:%._\+~#=]{2,256}\.[a-z]{2,5}\b([-a-zA-Z0-9#:%_\+.~#?&//=]*))', caseSensitive: false, dotAll: true);
static void _defaultOnLaunch(String url) async {
final re = RegExp('^https?://');
final fullUrl = re.hasMatch(url) ? url : 'http://$url';
if (await canLaunch(fullUrl)) {
await launch(fullUrl);
}
}
LinkedTextEditingController({
String text,
RegExp regexp,
this.linkStyle,
this.onTap = _defaultOnLaunch,
}) : linkRegexp = regexp ?? _defaultRegExp,
super(text: text);
LinkedTextEditingController.fromValue(
TextEditingValue value, {
RegExp regexp,
this.linkStyle,
this.onTap = _defaultOnLaunch,
}) : linkRegexp = regexp ?? _defaultRegExp,
assert(
value == null || !value.composing.isValid || value.isComposingRangeValid,
'New TextEditingValue $value has an invalid non-empty composing range '
'${value.composing}. It is recommended to use a valid composing range, '
'even for readonly text fields',
),
super.fromValue(value ?? TextEditingValue.empty);
#override
TextSpan buildTextSpan({TextStyle style, bool withComposing}) {
List<TextSpan> children = [];
text.splitMapJoin(
linkRegexp,
onMatch: (Match match) {
children.add(
TextSpan(
text: match[0],
style: linkStyle,
recognizer: onTap == null ? null : TapGestureRecognizer()
..onTap = () => onTap(match[0]),
),
);
return null;
},
onNonMatch: (String span) {
children.add(TextSpan(text: span, style: style));
return span;
},
);
return TextSpan(style: style, children: children);
}
}
as Durdu suggested, you can use RichText to achieve different color text. Just need to put multiple TextSpan with different color using TextStyle. Sample as below
Container(
margin: const EdgeInsets.only(left: 20.0, right: 20.0, top: 10.0, bottom: 10.0),
child: RichText(
textAlign: TextAlign.center,
text: TextSpan(
children: [
TextSpan(
text: 'By clicking sign up, you have read and agreed to our ',
style: TextStyle(color: Colors.black54),
),
TextSpan(
text: 'Terms & Conditions',
style: TextStyle(color: Colors.blue),
recognizer: TapGestureRecognizer()
..onTap = () {
print('Tapped on hyperlink');
},
),
TextSpan(
text: '.',
style: TextStyle(color: Colors.black54),
),
],
),
),
),
Hope this clears and solve your problem.
If you just want to change the color or font for the text in the textfield:
Text("Hello",
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w900))
If you want to use multiple styles you should check, you should check RichText.
The RichText widget displays text that uses multiple different styles.
RichText(
text: TextSpan(
text: 'Hello ',
style: TextStyle(color: Colors.black, fontWeight: FontWeight.w900)),
children: <TextSpan>[
TextSpan(text: 'bold', style: TextStyle(fontWeight: FontWeight.bold)),
TextSpan(text: ' world!'),
],
),
)