How do we print the int value in Text widget? I tried using '$num' but it just come out as instance of num.
This is what i tried so far
Text(
'$widget.count'+'. ',
style: TextStyle(
fontFamily: 'sansPro',
fontSize: 15,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
In your specific case you need to wrap the data with {}, So update the code to the following,
Text(
'${widget.count}''. ',
//...
);
And for more details:
To "print" or "render" a num value that is an int or a double in dart you can use the .toString() method on the variable. You can also use "String Interpolation" that is to evaluate a variable or an expression in a String.
For Example to create a Text widget that renders the a variable X:
Text(x.toString());
And using String Interpolation, you can use:
Text("$x");
If the variable needs to be evaluated as a part of an expression, That is if the vailable is part of an Object or you want to apply an operation before evaluating the final value, then the expression needs to be wrapped within {}, the code for that would be
Text("${x * 100}");
Text widget accept only data in a String format so you can get value in a int or double format and while displaying it convert it into String format. Consider a code snippet like a below:
intValueCount.toString()
Related
I have the following function, where within a ListBody I map List values, I have a time parameter that returns a time. This contains unnecessary digits and I want to format it.
In other normal List situations I use the function
var timeFormat = DateFormat("HH:mm");
String timetest = timeFormat.format(my_data);
How can I implement my above function to format the time in the below RichText, where I enter data into TextSpan from the map, and cannot build it as a var outside and then call it in?
var mappedValues = ListBody(
children: [...mappedList.map((m) => RichText (
text: TextSpan(
children: <TextSpan> [
TextSpan(text: m.time!.toLocal().toString(), style: TextStyle(
fontSize: 18 ,
fontWeight: FontWeight.w400,
color: Color(0xff2F2F2F),
fontFamily: 'DMSans'
)
),
]
)))]);
Thank you
Update
Example of initial output
2022-03-05 23:24:00.000
My function will turn it to
23:24
Then you should be able to create a method within this widget that takes the Datetime (m.time) as input and returns the formatted time, as:
String getFormattedTime(DateTime time) {
var timeFormat = DateFormat("HH:mm");
String timePortion = timeFormat.format(time);
return timePortion;
}
Then inside your widget just call it:
TextSpan(text: getFormattedTime(m.time!))
You could also move this method into a common utility class so you can reuse it throughout your app. Let me know if that’s what you looking for and works for your purposes.
Check out this Gist (make sure to run it through DartPad) that I created that illustrates my point. Another suggestion would be to use ListView in favor or ListBody as it is more robust.
You should get output that looks like this:
Let me know if that's clear.
For example I have a list of TextSpan:
List<TextSpan> listTextSpan = [TextSpan(text: "Hello"), TextSpan(text: "World")];
then:
AutoSizeText.rich(
TextSpan(
children: listTextSpan,
)),
So I want to make the list of TextSpan as a single text, That I'll be able to return
AutoSizeText.rich(
TextSpan(
text: singleText,
)),
You can use the fold method in order to combine every item on a list into a single value, the shape of the fold method looks like this:
var result = list.fold(initial, (previous, current) => result);
So in your case, if you just want to get a string of the text of every TextSpan, you would do it like this:
String singleText = listTextSpan.fold(
'',
(prev, curr) => '$prev ${curr.text!}');
the initial value is an empty string and you take the previous value, which is the current string, and add to it a space and the text of the current TextSpan, also note that this will throw an error if one of your text spans does not have a text property, in order to avoid this, you must replace curr.text! to curr.text ?? 'whatever you want'
If you still have issues understanding how the fold method works, you can check the documentation
As the question states, I would like to supply a default value to a Text Widget. I have four Text widgets. I use a variable in each Text Widget to display data. There is a chance that some data may not exist depending on the user and I would like to be able to default these Text Widgets to 0 if the value doesn't exist to prevent an error. Is this possible? Thanks!
Below is how it is currently.
Text(
'\$${quarter['data'][0].funds}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold),
),
You can provide a default value using the ?? operator, which returns the expression on its left unless that expression’s value is null, in which case it evaluates and returns the expression on its right (and you might need to add question marks for conditional property access in case quarter['data'] and quarter['data'][0] are nullable):
Text(
'\$${quarter['data']?[0]?.funds ?? 0}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
)
To safely access the funds at an index of the quarter['data'] list, you can create a helper method:
int fundsAt(int index) {
// This will return 0 if no element exists at the given index
return index >= 0 && index < quarter['data'].length
? quarter['data'][index].funds
: 0;
}
Here is the example of using fundsAt():
Text(
'\$${fundsAt(0)}',
style: TextStyle(
color: Colors.black,
fontWeight: FontWeight.bold,
),
)
You can try something like this :
'\$${quarter['data'][0].funds ?? 0}'
You can try these:
If the value can be null, then you can try this:
Text(myNullableData ?? "Default value");
Text(myNullableData == null ? "" : "Default value");
The ?? operator use your value if it is not null. If yes, it will use the default value you want.
Otherwise if some data may not exist depending means that the variable can be just an empty string: '""', then you can use the ?: operator:
Text(myData == "" ? "Default value" : myData);
Why can't I set the accents as a color?
This is my code :
Text('Hello',
style: TextStyle(color: Colors.accents),
)
In reality accents is not a color but rather a list(const List accents) that contains a lot of colors (accent colors).
Its implementation is :
static const List<MaterialAccentColor> accents = <MaterialAccentColor>[
redAccent,
pinkAccent,
purpleAccent,
deepPurpleAccent,
indigoAccent,
blueAccent,
lightBlueAccent,
cyanAccent,
tealAccent,
greenAccent,
lightGreenAccent,
limeAccent,
yellowAccent,
amberAccent,
orangeAccent,
deepOrangeAccent,
]
You can find it on the flutter website via this link
Now that we know it's a list, to retrieve one of its elements, just do List_name[element_index]. So in our case we'll do accents [color_index].
A small example of use :
Text('Hello',
style: TextStyle(color: Colors.accents[0]),
),
Colors.accents[0] for redAccent
Thanks.
Hi #martiX4 i found that you are passing invalid type to TextStyle widget now as answer given by #abhishek you can use index accents[index] based on your condition
for example if you use redAccent then you can use
List<MaterialAccentColor> accents = <MaterialAccentColor>[
redAccent,blueAccent];
// accents[0] => for redAccent
// accents[0] => for blueAccent
Text('Hello', style: TextStyle(color: Colors.accents[0]),)
accents is List so you can't be assigned to the color
/// The material design accent color swatches.
static const List<MaterialAccentColor> accents = <MaterialAccentColor>[
redAccent,
pinkAccent,
purpleAccent,
deepPurpleAccent,
indigoAccent,
blueAccent,
lightBlueAccent,
cyanAccent,
tealAccent,
greenAccent,
lightGreenAccent,
limeAccent,
yellowAccent,
amberAccent,
orangeAccent,
deepOrangeAccent,
];
you can use accents color using index value
Text('Hello',
style: TextStyle(color: Colors.accents[0]),
)
I am trying to generate a list of dropdown options for my user. I have created a custom model to use and here it is:
class UserFontModel {
String fontFamily;
FontWeight fontWeight;
UserFontModel({this.fontFamily, this.fontWeight});
}
I then create an instance here:
List<UserFontModel> _fonts = [
UserFontModel(fontFamily: 'Bold', fontWeight: FontWeight.w700),
UserFontModel(fontFamily: 'Medium', fontWeight: FontWeight.w500),
UserFontModel(fontFamily: 'Regular', fontWeight: FontWeight.w400),
UserFontModel(fontFamily: 'Light', fontWeight: FontWeight.w300),
UserFontModel(fontFamily: 'Thin', fontWeight: FontWeight.w100),
];
I then create a dropdown menu with the items based on the above list:
new DropdownButton<String>(
hint: Text('Style'),
items: _fonts.map((fonts) => DropdownMenuItem<String> (
child: Container(
width: MediaQuery.of(context).size.width * 0.2,
child: Text(fonts.fontFamily, style: TextStyle(fontWeight: fonts.fontWeight),),
),
)).toList(),
onChanged: (String _) {
setState(() {
print(_);
});
},
),
But for some reason (probably a simple one that i'm missing), I can't work out why i'm getting the error:
A non-null String must be provided to a Text widget.
Any thoughts?
Well, my obvious thought is: post a minimal compilable example, with the full error message.
But another thought that might actually help you to find the mistake yourself is: don't make programming hard on yourself. You are human. Let the machine do the hard work, that is the way we should do this. You want to make sure you never accidentally have a null value in your models? Then write the model so a null value is not possible without your compiler telling you exactly where you failed at compile time:
class UserFontModel {
final String fontFamily;
final FontWeight fontWeight;
const UserFontModel({#required this.fontFamily, #required this.fontWeight})
: assert(fontFamily != null),
assert(fontWeight != null);
}
This class is not instatiable without both fontFamily and fontWeight given, it will warn you at runtime, if you gave one and it was null and it makes sure you cannot accidentally change the fields after they have been checked to be correct. The point here is: this is your compiler. the machine does the work for you. As it should be.
This will not fix your actual problem, but it should fix your problem of not finding your actual problem.