I have some texts that contain emojis and I'm trying to show them on the Text widget. However, they seem to be shown as foreign characters. Does Flutter support showing emojis? should work for both iOS and Android
The Problem
As of now, unfortunately, Flutter uses the default Emojis supported on a given platform. Therefore, when building a cross-platform app you may face issues of Emojis showing on certain devices and not on others.
The Solution
The solution I settled for is to use a custom Emoji font such as Emoji One and RichText widget instead of the basic Text widget.
With this, you can simply have:
RichText(
text: TextSpan(
children: <TextSpan>[
TextSpan(
text: 'Hello', // non-emoji characters
),
TextSpan(
text: '🧭 🏳️\u200d🌈', // emoji characters
style: TextStyle(
fontFamily: 'EmojiOne',
),
),
],
),
);
Generalized Solution
With this idea, we can even create a custom widget that given a string, builds a RichText object with all the TextSpans autocreated:
class EmojiText extends StatelessWidget {
const EmojiText({
Key key,
#required this.text,
}) : assert(text != null),
super(key: key);
final String text;
#override
Widget build(BuildContext context) {
return RichText(
text: _buildText(this.text),
);
}
TextSpan _buildText(String text) {
final children = <TextSpan>[];
final runes = text.runes;
for (int i = 0; i < runes.length; /* empty */ ) {
int current = runes.elementAt(i);
// we assume that everything that is not
// in Extended-ASCII set is an emoji...
final isEmoji = current > 255;
final shouldBreak = isEmoji
? (x) => x <= 255
: (x) => x > 255;
final chunk = <int>[];
while (! shouldBreak(current)) {
chunk.add(current);
if (++i >= runes.length) break;
current = runes.elementAt(i);
}
children.add(
TextSpan(
text: String.fromCharCodes(chunk),
style: TextStyle(
fontFamily: isEmoji ? 'EmojiOne' : null,
),
),
);
}
return TextSpan(children: children);
}
}
Which can be used as:
EmojiText(text: 'Hello there: 🧭 🏳️\u200d🌈');
This has the advantage of having the consistent support of Emojis on your app that you can control on different platforms.
The downside is that it will add some MBs to your app.
You can insert emoji in the text field through following way:
If you're on Mac, you can hit Control + Command + Space. Windows users can hit the "Windows key" + ; (semicolon).
Copy pasted the instruction from #Reso Coder
https://www.youtube.com/watch?v=KfuUkq2cLZU&t=15s
I tested on mac and it works.
Flutter supports emoji. Here's some code that demonstrates emoji text entry. (If you're seeing foreign characters, it's likely that you're decoding bytes as ASCII instead of UTF-8; we can show you how to fix this if you update your question with code that demonstrates the problem.)
import 'dart:async';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
home: new MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key}) : super(key: key);
#override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _message = '🐣';
Future<String> _promptForString(String label, { String hintText }) {
final TextEditingController controller = new TextEditingController();
return showDialog(
context: context,
child: new AlertDialog(
title: new Text(label),
content: new TextFormField(
controller: controller,
decoration: new InputDecoration(hintText: hintText),
),
actions: <Widget>[
new FlatButton(
onPressed: () => Navigator.pop(context),
child: const Text('CANCEL'),
),
new FlatButton(
onPressed: () => Navigator.pop(context, controller.text),
child: const Text('OK'),
),
],
),
);
}
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(_message),
),
body: new Center(
child: new Text(_message, style: Theme.of(context).textTheme.display2),
),
floatingActionButton: new FloatingActionButton(
child: new Icon(Icons.edit),
onPressed: () async {
String message = await _promptForString('New text', hintText: 'Try emoji!');
if (!mounted)
return;
setState(() {
_message = message;
});
},
),
);
}
}
If you just want to include emoji in Text widget, you can copy emoji from somewhere else and paste it inside the text widget.
I use GeteMoji to copy emojis.
See the Output Screenshot
CODE : See 8th Row.
Widget build(BuildContext context) {
return Center(
child: Container(
alignment: Alignment.center,
color: Colors.deepPurple,
//width: 200.0,
//height: 100.0,
child: Text("Emoji 🤣 ",
style: TextStyle(
fontFamily: 'Raleway',
fontSize: 40,
decoration: TextDecoration.none,
color: Colors.white
))));
}
For full emoji compatibility (at least in android, not all emojis are supported in old OS versions) you can use the google free font Noto Color Emoji at https://www.google.com/get/noto/#emoji-zsye-color
Add it to the fonts folder
add in pubspec.yaml
fonts:
- family: NotoEmoji
fonts:
- asset: fonts/NotoColorEmoji.ttf
weight: 400
use with TextStyle
Text("🤑", TextStyle(fontFamily: 'NotoEmoji'))
When an emoji is not showing up, the issue is most likely the font you are using.
Before trying out an emoji font package, you can give the text field an empty string as fontFamily or try out the default font options packaged with flutter.
This will prevent adding dependencies that are not needed.
for example this emoji was not showing on android with 'Product Sans' as fontFamily, i simply added an empty string and font family for the text field, and that fixed the issue.
Text('₦', TextStyle(fontFamily: ''))
You can easily use the fontFamily as a style to solve the problem
I used it with the package
auto_size_text: ^2.1.0
AutoSizeText(
lesson.FullExercise,
textAlign: TextAlign.justify,
style:TextStyle(
fontFamily: 'EmojiOne',
),
),
Good note to mention
If you want to store data in MySQL and the text contains Emojis you need to change the collection of the text to utf8mb4
Related
I'm trying to set the default SF font for my app but I always get Roboto font. I tried to use CupertinoApp and .SF Pro Text as fontfamily for the text but I got Roboto font. I also tried to use real iphone device but didnt work.
In this example I got same font type.
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'Roboto Text',
style: TextStyle(fontSize: 38, fontFamily: 'Roboto'),
),
const Text(
'SF Text',
style: TextStyle(
fontSize: 38,
fontFamily: '.SF UI Text',
),
),
],
),
),
);
}
}
I have a list that is populated with the return data of various var's
This list also has a text element preceding the data
I want to have separate weight, size etc for the initial text and then the String being passed in
I have tried RichText and TextStyle but needed a text function, not a list for it to work correctly
Here is the List which is then passed into a function which pushes it to ShowDialog
For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400
List data = [
"Line: $pln",
"Departed from: $originname",
"Destination: $destname",
"Last seen: $recordedattime",
];
ShowDialog, where message is the list from previous function
title: Text(title),
content: SingleChildScrollView(
child: ListBody(
children: <Widget>[
Text(message,
style: TextStyle(
fontSize: 18,
color: Color(0xff2F2F2F),
fontWeight: FontWeight.w500,
...
Try creating a new widget for it, this way you can modify the build however you desire easily.
class NewTextWidget extends StatelessWidget {
final String prefix;
final String value;
NewTextWidget({required String message, Key? key})
: prefix = message.split(": ")[0],
value = message.split(": ")[1],
super(key: key);
#override
Widget build(BuildContext context) {
return RichText(
text: TextSpan(
text: prefix,
style: const TextStyle(fontWeight: FontWeight.w600),
children: [
TextSpan(
text: value,
style: const TextStyle(fontWeight: FontWeight.w400))
]),
);
}
}
The NewTextWidget expects the message with the prefix: value format.
So when you call it you need to update your ListBody as:
ListBody(
children: data.map((String message) => NewTextWidget(message: message)).toList()
)
As I'm learning Flutter I've come to navigation. I want to pass data between screens similarly to passing data between Activities in Android and passing data between View Controllers in iOS. How do I do it in Flutter?
Related questions:
The best way to passing data between widgets in Flutter
Flutter pass data between widgets?
Flutter/ How to pass and get data between Statefulwidget
This answer will cover both passing data forward and passing data back. Unlike Android Activities and iOS ViewControllers, different screens in Flutter are just widgets. Navigating between them involves creating something called a route and using the Navigator to push and pop the routes on and off the stack.
Passing data forward to the next screen
To send data to the next screen you do the following things:
Make the SecondScreen constructor take a parameter for the type of data that you want to send to it. In this particular example, the data is defined to be a String value and is set here with this.text.
class SecondScreen extends StatelessWidget {
final String text;
SecondScreen({Key key, #required this.text}) : super(key: key);
...
Then use the Navigator in the FirstScreen widget to push a route to the SecondScreen widget. You put the data that you want to send as a parameter in its constructor.
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(text: 'Hello',),
));
The full code for main.dart is here:
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Flutter',
home: FirstScreen(),
));
}
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() {
return _FirstScreenState();
}
}
class _FirstScreenState extends State<FirstScreen> {
// this allows us to access the TextField text
TextEditingController textFieldController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('First screen')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(32.0),
child: TextField(
controller: textFieldController,
style: TextStyle(
fontSize: 24,
color: Colors.black,
),
),
),
RaisedButton(
child: Text(
'Go to second screen',
style: TextStyle(fontSize: 24),
),
onPressed: () {
_sendDataToSecondScreen(context);
},
)
],
),
);
}
// get the text in the TextField and start the Second Screen
void _sendDataToSecondScreen(BuildContext context) {
String textToSend = textFieldController.text;
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(text: textToSend,),
));
}
}
class SecondScreen extends StatelessWidget {
final String text;
// receive data from the FirstScreen as a parameter
SecondScreen({Key key, #required this.text}) : super(key: key);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second screen')),
body: Center(
child: Text(
text,
style: TextStyle(fontSize: 24),
),
),
);
}
}
Passing data back to the previous screen
When passing data back you need to do the following things:
In the FirstScreen, use the Navigator to push (start) the SecondScreen in an async method and wait for the result that it will return when it finishes.
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(),
));
In the SecondScreen, include the data that you want to pass back as a parameter when you pop the Navigator.
Navigator.pop(context, 'Hello');
Then in the FirstScreen the await will finish and you can use the result.
setState(() {
text = result;
});
Here is the complete code for main.dart for your reference.
import 'package:flutter/material.dart';
void main() {
runApp(MaterialApp(
title: 'Flutter',
home: FirstScreen(),
));
}
class FirstScreen extends StatefulWidget {
#override
_FirstScreenState createState() {
return _FirstScreenState();
}
}
class _FirstScreenState extends State<FirstScreen> {
String text = 'Text';
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('First screen')),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(32.0),
child: Text(
text,
style: TextStyle(fontSize: 24),
),
),
RaisedButton(
child: Text(
'Go to second screen',
style: TextStyle(fontSize: 24),
),
onPressed: () {
_awaitReturnValueFromSecondScreen(context);
},
)
],
),
),
);
}
void _awaitReturnValueFromSecondScreen(BuildContext context) async {
// start the SecondScreen and wait for it to finish with a result
final result = await Navigator.push(
context,
MaterialPageRoute(
builder: (context) => SecondScreen(),
));
// after the SecondScreen result comes back update the Text widget with it
setState(() {
text = result;
});
}
}
class SecondScreen extends StatefulWidget {
#override
_SecondScreenState createState() {
return _SecondScreenState();
}
}
class _SecondScreenState extends State<SecondScreen> {
// this allows us to access the TextField text
TextEditingController textFieldController = TextEditingController();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Second screen')),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(32.0),
child: TextField(
controller: textFieldController,
style: TextStyle(
fontSize: 24,
color: Colors.black,
),
),
),
RaisedButton(
child: Text(
'Send text back',
style: TextStyle(fontSize: 24),
),
onPressed: () {
_sendDataBack(context);
},
)
],
),
);
}
// get the text in the TextField and send it back to the FirstScreen
void _sendDataBack(BuildContext context) {
String textToSendBack = textFieldController.text;
Navigator.pop(context, textToSendBack);
}
}
This solution is very easy by passing variables in constructor:
first page:
Navigator.of(context).push(MaterialPageRoute(builder:(context)=>SecondPage('something')));
second page:
class SecondPage extends StatefulWidget {
String something;
SecondPage(this.something);
#override
State<StatefulWidget> createState() {
return SecondPageState(this.something);
}
}
class SecondPageState extends State<SecondPage> {
String something;
SecondPageState(this.something);
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
//now you have passing variable
title: Text(something),
),
...
}
Get Perfect Solution :
From 1st Screen navigate to others as:
Navigator.pushNamed(context, "second",arguments: {"name" :
"Bijendra", "rollNo": 65210});
},
On Second Screen in build method get as :
#override
Widget build(BuildContext context) {
final Map<String, Object>rcvdData = ModalRoute.of(context).settings.arguments;
print("rcvd fdata ${rcvdData['name']}");
print("rcvd fdata ${rcvdData}");
return Scaffold(appBar: AppBar(title: Text("Second")),
body: Container(child: Column(children: <Widget>[
Text("Second"),
],),),);
}
Easiest way
FirstPage.dart
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => PasswordRoute(usernameController)));
//usernameController is String value,If you want to pass multiple values add all
SecondPage.dart
class PasswordRoute extends StatefulWidget {
final String usernameController;//if you have multiple values add here
PasswordRoute(this.usernameController, {Key key}): super(key: key);//add also..example this.abc,this...
#override
State<StatefulWidget> createState() => _PasswordPageState();
}
class _PasswordPageState extends State<PasswordRoute> {
#override
Widget build(BuildContext context) {
...child: Text(widget.usernameController);
}
}
Answers above are useful for a small app, but if you want to remove the headache of continuously worrying about a widgets state, Google presented the Provider package.
https://pub.dev/packages/provider
Have a look into that one, or watch these videos from Andrea Bizzotto:
https://www.youtube.com/watch?v=MkFjtCov62g // Provider: The Essential Guide
https://www.youtube.com/watch?v=O71rYKcxUgA&t=258s // Provider: Introduction
Learn how to use the Provider package, and you are set for life :)
First Screen :
//send data to second screen
Navigator.push(context, MaterialPageRoute(builder: (context) {
return WelcomeUser(usernameController.text);
}));
Second Screen :
//fetch data from first screen
final String username;
WelcomeUser(this.username);
//use data to display
body: Container(
child: Center(
child: Text("Welcome "+widget.username,
textAlign: TextAlign.center,
),
),
),
Navigators in Flutter are similar to the Intent in Android.
There are two classes we are dealing with FirstScreen and SecondScreen.
In order to pass the data between the first screen to second do the following:
First of all add parameter in the SecondScreen class constructor
Now in the FirstScreen class provide the parameter
Navigator.push(context, MaterialPageRoute(builder: (context)=>SecondScreen(key_name:"Desired Data"));
So in the above line the "key_name" is the name of the parameter given in the SecondScreen class.
The "Desired Data" is data should be passed through the key to the SecondScreen class.
That's it you are done!!!
Passing Data to back screen flutter
Home Page
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
import 'package:sqflite_offline/View/Add_data.dart';
class HomeScreen extends StatefulWidget {
const HomeScreen({super.key});
#override
State<HomeScreen> createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
List<Method> items = []; // => List of items that come form next page.
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Hello"),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
Navigator.of(context)
.push<Method>(MaterialPageRoute(builder: (_) => AddData()))
// fetching data form next page.
.then((value) => setState(() {
if (value?.title_Ctr != "" && value?.desc_Ctr != "") {
items.add(Method(
title_Ctr: value!.title_Ctr,
desc_Ctr: value.desc_Ctr));
}
}));
},
child: Icon(Icons.add),
),
body: items.isNotEmpty
? Column(children: [
Expanded(
child: ListView.builder(
itemCount: items.length,
itemBuilder: ((context, index) {
return Container(
margin:
EdgeInsets.only(top: 10, left: 10, right: 10),
padding: EdgeInsets.only(left: 10, right: 10),
height: 80,
decoration: BoxDecoration(
color: Colors.pinkAccent,
borderRadius: BorderRadius.circular(10)),
child: Center(
child: ListTile(
title: Text(items[index].title_Ctr),
subtitle: Text(items[index].desc_Ctr),
leading: Icon(Icons.emoji_people),
),
),
);
})))
])
: Center(
child: Text("No Record Found"),
));
}
}
Add List Page
import 'package:flutter/material.dart';
import 'package:flutter/src/widgets/container.dart';
import 'package:flutter/src/widgets/framework.dart';
class AddData extends StatefulWidget {
const AddData({super.key});
#override
State<AddData> createState() => _AddDataState();
}
// Creating a Class and constructor.
class Method {
late String title_Ctr;
late String desc_Ctr;
Method({required this.title_Ctr, required this.desc_Ctr});
}
class _AddDataState extends State<AddData> {
// Creating a TextEditingController for two Fiends,
//one is for title TextField and second is for Description TextField.
TextEditingController titleCtr = TextEditingController();
TextEditingController descCtr = TextEditingController();
// Creating a Method for Passing a data to back page.
OnPressed(BuildContext context) {
var data = Method(title_Ctr: titleCtr.text, desc_Ctr: descCtr.text);
Navigator.pop(context, data);
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Add Data")),
body: Form(child: Builder(builder: (context) {
return Column(children: [
TextFormField(
controller: titleCtr,
decoration: InputDecoration(hintText: "title"),
validator: (value) {
var newValue = value ?? "";
if (newValue.isEmpty) {
return 'title is Required';
}
return null;
},
),
TextFormField(
controller: descCtr,
decoration: InputDecoration(hintText: "Description"),
validator: (value) {
var newValue = value ?? "";
if (newValue.isEmpty) {
return 'Discription is Required';
}
return null;
},
),
MaterialButton(
color: Colors.red,
onPressed: () {
if (Form.of(context)?.validate() ?? false) {
OnPressed(context);
}
},
child: Text("Save"),
)
]);
})));
}
}
screenshot
1) From where you want to push :
onPressed: () async {
await Navigator.pushNamed(context, '/edit',
arguments: userData);
setState(() {
userData = userData;
});}
2) From Where you want to pop :
void updateData() async{
WorldTime instance = locations;
await instance.getData();
Navigator.pop(context, userData);
}
If you use get package then try this . passing data with get package
check get package package link
Here's another approach.
Nothing wrong with the other answers. I've tried all of the methods mentioned using global wide widgets like provider, third-party solutions, Navigator arguments, etc. This approach differs by allowing one to chain calls and pass precise data of any type required to the widget using it. We can also gain access to a completion handler event and can use this technique without being constrained to Navigator objects.
Here's the tldr:
tldr; We have to turn our thinking on its head a bit. Data can be
passed to the called widget when you navigate to it by using final
arguments with default values in the destination widget. Using an
optional function you can get data back from the 'child' (destination)
widget.
The complete explanation can be found using this SO answer., (Gist)
I just want to be here to help that 1% who might go through what I did Lol
Don't forget to put an "await" infront of "Navigator.push" in the first page,
otherwise no data will be returned to the first page when you pop from the second page...
Passing Data to back screen flutter
First Screen
final result = await Navigator.of(context).push(MaterialPageRoute(builder: (context)=>const PaymentScreen()));
Second Screen
String selected = "Credit/Debit";
Navigator.pop(context,selected);
I have a Text widget which can be truncated if it exceeds a certain size:
ConstrainedBox(
constraints: BoxConstraints(maxHeight: 50.0),
child: Text(
widget.review,
overflow: TextOverflow.ellipsis,
)
);
Or max number of lines:
RichText(
maxLines: 2,
overflow: TextOverflow.ellipsis,
text: TextSpan(
style: TextStyle(color: Colors.black),
text: widget.review,
));
My goal is to have the text expandable only if an overflow occurred. Is there a proper way of checking if the text overflowed?
What I've tried
I have found that in RichText, there is a RenderParagraph renderObject , which has a private property TextPainter _textPainter which has a bool didExceedMaxLines.
In short, I just need to access richText.renderObject._textPainter.didExceedMaxLines but as you can see, it is made private with the underscore.
I found a way to do it. Full code below, but in short:
Use a LayoutBuilder to determine how much space we have.
Use a TextPainter to simulate the render of the text within the space.
Here's the full demo app:
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Text Overflow Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(title: Text("DEMO")),
body: TextOverflowDemo(),
),
);
}
}
class TextOverflowDemo extends StatefulWidget {
#override
_EditorState createState() => _EditorState();
}
class _EditorState extends State<TextOverflowDemo> {
var controller = TextEditingController();
#override
void initState() {
controller.addListener(() {
setState(() {
mytext = controller.text;
});
});
controller.text = "This is a long overflowing text!!!";
super.initState();
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
String mytext = "";
#override
Widget build(BuildContext context) {
int maxLines = 1;
double fontSize = 30.0;
return Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
children: <Widget>[
LayoutBuilder(builder: (context, size) {
// Build the textspan
var span = TextSpan(
text: mytext,
style: TextStyle(fontSize: fontSize),
);
// Use a textpainter to determine if it will exceed max lines
var tp = TextPainter(
maxLines: maxLines,
textAlign: TextAlign.left,
textDirection: TextDirection.ltr,
text: span,
);
// trigger it to layout
tp.layout(maxWidth: size.maxWidth);
// whether the text overflowed or not
var exceeded = tp.didExceedMaxLines;
return Column(children: <Widget>[
Text.rich(
span,
overflow: TextOverflow.ellipsis,
maxLines: maxLines,
),
Text(exceeded ? "Overflowed!" : "Not overflowed yet.")
]);
}),
TextField(
controller: controller,
),
],
),
);
}
}
There is a shorter way to get an answer if text is overflowed or not. You just need to define textStyle and get the answer from this method
bool hasTextOverflow(
String text,
TextStyle style,
{double minWidth = 0,
double maxWidth = double.infinity,
int maxLines = 2
}) {
final TextPainter textPainter = TextPainter(
text: TextSpan(text: text, style: style),
maxLines: maxLines,
textDirection: TextDirection.ltr,
)..layout(minWidth: minWidth, maxWidth: maxWidth);
return textPainter.didExceedMaxLines;
}
You can use a flutter plug-in auto_size_text at pub.dev.
When the text is get overflowed, you can set some widget to be appeared.
int maxLines = 3;
String caption = 'Your caption is here';
return AutoSizeText(
caption,
maxLines: maxLines,
style: TextStyle(fontSize: 20),
minFontSize: 15,
overflowReplacement: Column( // This widget will be replaced.
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
caption,
maxLines: maxLines,
overflow: TextOverflow.ellipsis,
),
Text(
"Show more",
style: TextStyle(color: PrimaryColor.kGrey),
)
],
),
);
Made my own Widget i use it cross the project, it take Text widget in the constructor and reads the properties of it.
import 'package:flutter/material.dart';
class OverflowDetectorText extends StatelessWidget {
final Text child;
OverflowDetectorText({
Key? key,
required this.child,
}) : super(key: key);
#override
Widget build(BuildContext context) {
var tp = TextPainter(
maxLines: child.maxLines,
textAlign: child.textAlign ?? TextAlign.start,
textDirection: child.textDirection ?? TextDirection.ltr,
text: child.textSpan ?? TextSpan(
text: child.data,
style: child.style,
),
);
return LayoutBuilder(
builder: (context, constrains) {
tp.layout(maxWidth: constrains.maxWidth);
final overflowed = tp.didExceedMaxLines;
if (overflowed) {
//You can wrap your Text `child` with anything
}
return child;
},
);
}
}
I want to build a form where I have multiple TextField widgets, and want to have a button that composes and e-mail when pressed, by passing the data gathered from these fields.
For this, I started building an InheritedWidget to contain TextField-s, and based on the action passed in the constructor - functionality not yet included in the code below - it would return a different text from via toString method override.
As I understood, an InheritedWidget holds it's value as long as it is part of the current Widget tree (so, for example, if I navigate from the form it gets destroyed and the value is lost).
Here is how I built my TextForm using InheritedWidget:
class TextInheritedWidget extends InheritedWidget {
const TextInheritedWidget({
Key key,
this.text,
Widget child}) : super(key: key, child: child);
final String text;
#override
bool updateShouldNotify(TextInheritedWidget old) {
return text != old.text;
}
static TextInheritedWidget of(BuildContext context) {
return context.inheritFromWidgetOfExactType(TextInheritedWidget);
}
}
class TextInputWidget extends StatefulWidget {
#override
createState() => new TextInputWidgetState();
}
class TextInputWidgetState extends State<TextInputWidget> {
String text;
TextEditingController textInputController = new TextEditingController();
#override
Widget build(BuildContext context) {
return new TextInheritedWidget(
text: text,
child: new TextField(
controller: textInputController,
decoration: new InputDecoration(
hintText: adoptionHintText
),
onChanged: (text) {
setState(() {
this.text = textInputController.text;
});
},
),
);
}
#override
String toString({DiagnosticLevel minLevel: DiagnosticLevel.debug}) {
// TODO: implement toString
return 'Név: ' + text;
}
}
And here is the button that launches the e-mail sending:
TextInputWidget nameInputWidget = new TextInputWidget();
TextInheritedWidget inherited = new TextInheritedWidget();
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Örökbefogadás'),
),
body: new Container(
padding: const EdgeInsets.all(5.0),
child: new ListView(
children: <Widget>[
new Text('Név:', style: infoText16BlackBold,),
nameInputWidget,
new FlatButton(onPressed: () {
launchAdoptionEmail(nameInputWidget.toString(), 'kutya');
},
child: new Text('Jelentkezem'))
],
),
),
);
}
My problem is that the nameInputWidget.toString() simply returns TextInputWidget (class name) and I can't seem to find a way to access the TextInputWidgetState.toString() method.
I know that TextInheritedWidget holds the text value properly, but I'm not sure how I could access that via my nameInputWidget object.
Shouldn't the TextInputWidget be able to access the data via the context the InheritedWidget uses to determine which Widget to update and store the value of?
This is not possible. Only children of an InheritedWidget can access it's properties
The solution would be to have your InheritedWidget somewhere above your Button. But that imply you'd have to refactor to take this into account.
Following Rémi's remarks, I came up with a working solution, albeit I'm pretty sure it is not the best and not to be followed on a massive scale, but should work fine for a couple of fields.
The solution comes by handling all TextField widgets inside one single State, alongside the e-mail composition.
In order to achieve a relatively clean code, we can use a custom function that build an input field with the appropriate data label, which accepts two input parameters: a String and a TextEditingController.
The label is also used to determine which variable the setState() method will pass the newly submitted text.
Widget buildTextInputRow(var label, TextEditingController textEditingController) {
return new ListView(
shrinkWrap: true,
children: <Widget>[
new Row(
children: <Widget>[
new Expanded(
child: new Container(
padding: const EdgeInsets.only(left: 5.0, top: 2.0, right: 5.0 ),
child: new Text(label, style: infoText16BlackBold)),
),
],
),
new Row(
children: <Widget>[
new Expanded(
child: new Container(
padding: const EdgeInsets.only(left: 5.0, right: 5.0),
child: new TextField(
controller: textEditingController,
decoration: new InputDecoration(hintText: adoptionHintText),
onChanged: (String str) {
setState(() {
switch(label) {
case 'Név':
tempName = 'Név: ' + textEditingController.text + '\r\n';
break;
case 'Kor':
tempAge = 'Kor: ' + textEditingController.text + '\r\n';
break;
case 'Cím':
tempAddress = 'Cím: ' + textEditingController.text + '\r\n';
break;
default:
break;
}
});
}
)),
),
],
)
],
);
}
The problem is obviously that you will need a new TextEditingController and a new String to store every new input you want the user to enter:
TextEditingController nameInputController = new TextEditingController();
var tempName;
TextEditingController ageInputController = new TextEditingController();
var tempAge;
TextEditingController addressInputController = new TextEditingController();
var tempAddress;
This will result in a lot of extra lines if you have a lot of fields, and you will also have to update the composeEmail() method accordingly, and the more fields you have, you will be more likely to forget a couple.
var emailBody;
composeEmail(){
emailBody = tempName + tempAge + tempAddress;
return emailBody;
}
Finally, it is time to build the form:
#override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text('Örökbefogadás'),
),
body: new ListView(
children: <Widget>[
buildTextInputRow('Név', nameInputController),
buildTextInputRow('Kor', ageInputController),
buildTextInputRow('Cím', addressInputController),
new FlatButton(onPressed: () { print(composeEmail()); }, child: new Text('test'))
],
),
);
}
For convenience, I just printed the e-mail body to the console while testing
I/flutter ( 9637): Név: Zoli
I/flutter ( 9637): Kor: 28
I/flutter ( 9637): Cím: Budapest
All this is handled in a single State.