How to define TextStyle in a conditional statement flutter - flutter

Might be a very obvious question, but I need to add a TextStyle in a conditional statement, but it seems to not be applying it. This is what I tried:
Text((() {
if (contract.active == true) {
TextStyle(fontSize: 18);
return 'active';
}
return 'inactive';
}())),
It is not applying the textStyle. thank you.

You can use ternary operator:
Text(
'dummy text',
style: contract.active == true ? TextStyle(color: Colors.red): TextStyle(color:Colors.blue),
)
I added this for only TextStyle, you can do it for Text if you want.
And one thing, contract.active is already bool you don't need to check its equality, you can use contract.active instead of contract.active == true.
You can change text like this:
Text(
contract.active ? 'active' :'inactive'
style: contract.active ? TextStyle(fontSize: 18) : TextStyle()
)

You are using an immediate anonymous function there. The first parameter of Text widget expects a string and your anonymous function returns that. The TextStyle object that you've created inside the function body doesn't do anything.
You need to change your implementation to (using immediate anonymous function):
Text(
(() {
if (contract.active) {
return "Active";
}
return "Inactive";
}()),
style: (() {
if (contract.active) {
return TextStyle(fontSize: 18);
}
return null;
}())
),
But the above code looks very odd, you can simply achieve that using ternary operator:
Text(contract.active ? "Active" : "Inactive",
style: active ? TextStyle(fontSize: 18) : null),

Related

How do I hide SpeedDialChild from SpeedChild if bool condition false(Flutter)

I am struggling to hide SpeedDialChild, when my noDoctorReply == false. I can't use if else conditions. I tried to code like below.
noDoctorReply == false
? SpeedDialChild(
child: Icon(Icons.stop_screen_share_outlined),
backgroundColor: Colors.green,
label: 'Complete Conversation',
labelStyle: TextStyle(fontSize: 18.0),
onTap: () {
_completeDialog();
},
)
: SpeedDialChild(),
But it got me to here.
Is there any way to hide this? Thank you.
EDIT: I used package called flutter_speed_dial.
You can use just if conditional state. While else is never needed to show up.
if(noDoctorReply) showMyWidget()
You can also check Visibility widget.

How to hide password ENTIRELY in flutter [duplicate]

This question already has answers here:
Flutter: obscureText, how to stop showing typed characters
(2 answers)
Closed last year.
I was searching a lot on the internet about how to hide password in TextFormField, the entirely one. Because obscureText doesn't hide all of it, they give a slightly every character you typed
screenshot
Is there any solution for this? Thx in advance
You need it on Android and iOs, right? Because on other platforms seems to be implemented by default like you want it.
In any case, try this:
class ObscuringTextEditingController extends TextEditingController {
ObscuringTextEditingController(String text) : super(text: text);
#override
TextSpan buildTextSpan({required BuildContext context, TextStyle? style, required bool withComposing}) {
var displayValue = '•' * value.text.length;
if (!value.composing.isValid || !withComposing) {
return TextSpan(style: style, text: displayValue);
}
final TextStyle composingStyle = style?.merge(
const TextStyle(decoration: TextDecoration.underline),
) ??
const TextStyle(decoration: TextDecoration.underline);
return TextSpan(
style: style,
children: <TextSpan>[
TextSpan(text: value.composing.textBefore(displayValue)),
TextSpan(
style: composingStyle,
text: value.composing.textInside(displayValue),
),
TextSpan(text: value.composing.textAfter(displayValue)),
],
);
}
}
Updated the original code from here

How to Flutter test TextThemes

I need to test the following piece of code to basically check if trailingIconButton == null then a certain text theme should be applied.
Text(
type == TileType.org
? orgInfo!.name!
: type == TileType.user
? '${userInfo!.firstName!} ${userInfo!.lastName!}'
: option!.title,
style: type == TileType.org
? Theme.of(context).textTheme.headline5
: type == TileType.user
? Theme.of(context).textTheme.headline6
: option!.trailingIconButton == null
? Theme.of(context).textTheme.bodyText2
: Theme.of(context)
.textTheme
.headline5!
.copyWith(fontSize: 18),
key: const Key('trailingIconButton'),
),
what I wrote
testWidgets('Creating Custom List (giving custom options)', (tester) async {
await tester.pumpWidget(createCustomListTileUser(
option: Options(
icon: const Icon(Icons.add),
title: 'henlo',
subtitle: 'yesh',
trailingIconButton: null)));
final Text text =
tester.firstWidget(find.byKey(const Key('trailingIconButton')));
//equals bodyText2
expect(text.style!.getTextStyle(),
equals(Theme.of(MockBuildContext()).textTheme.bodyText2));
});
The problem is that you're using different contexts to get theme which results in different themes. In your application you probably have defined a Theme which is returned when you're using Theme.of(context) but that's not the case in your tests. When you're doing Theme.of(MockBuildContext()) You're getting different one.
So to solve this you need to wrap your widgets with a theme provider with the same theme used in your application. Then use this code to compare themes:
expect(
text.style!.getTextStyle(),
equals(Theme.of(
tester.element(find.byKey(const Key('trailingIconButton'))))
.textTheme
.bodyText2));

Is it possible to supply a default value to a Text widget?

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);

How can I translate a CheckboxListTile in Flutter?

This is my code:
CheckboxListTile (
value: agree,
title: Text (AppLocalizations.of(context).translate('Do you accept the terms and conditions?'),
style: TextStyle(fontSize: 18)),
onChanged: (bool value) {
setState(() {
this.agree = value;
});
},
),
The error is:
a non null string must be provided to a text widget
Try adding a fallback text in the Text widget
Text(AppLocalizations.of(context).translate('Do you accept the terms and conditions?' ?? 'Do you accept the terms and conditions?');
If you want it to be translated, you have to check your folder: assets > lang
You will see all the translations that are in your project, I have put the following in the English one:
"DoYouAcceptTheTermsAndConditions?": "Do you accept the terms and conditions?",
And in Spanish:
"DoYouAcceptTheTermsAndConditions?": "¿Aceptas los términos y condiciones?",
If you have any questions, you can ask me questions: D
EDIT: My code now it looks like this:
CheckboxListTile (
title: Text(AppLocalizations.of(context).translate('DoYouAcceptTheTermsAndConditions?'),
style: TextStyle(fontSize: 18)),
value: agree,
onChanged: (bool value) {
setState(() {
this.agree = value;
});
},
),