How to style my text widget dynamically in flutter - flutter

I am new to flutter and I have an issue to change text style dynamically.
I fetch data from firestore database in map like this
Map data = {"amount": "", "type": ""}
Example data1
data = { "amount": "3000", "type": "income" }
Example data2
data = { "amount": "3000", "type": "expense" }
I want to print this data in text widget like
Text('$ : ${data['amount']', style: $data['type'])"
my style.dart
final textStyle income = TextStyle {
color: Colors.blue,
fontSize: 24,
}
final textStyle expense = TextStyle {
color: Colors.red,
fontSize: 24
}
Can anyone suggest how I can do that?

You can do a condition check to change based on type like
Text('${data['amount']}', style: data['type'] == "expense" ? TextStyle(fontSize: 20, color: Colors.red) : TextStyle(fontSize: 12, color: Colors.blue)),

Related

How to change Text color with Get in Flutter

How can i change my Texts color immedietly
TextStyle get headingStyle {
return GoogleFonts.lato(
textStyle: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
color:Get.isDarkMode?Colors.white:Colors.black);
}
color changes when i hot reloud but doesn't change when i clicked the button(button changes isDarkMode )
Try put the Obx.
It's create an observable in your code
TextStyle get headingStyle {
return Obx(() => GoogleFonts.lato(
textStyle: TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
color:Get.isDarkMode?Colors.white:Colors.black));
}

flutter, fetching dummy local json

i have local dummy json and i want to put it on title but the variables forms does not defined, i don't understand how to call the forms
the Json and title both are in different stateless widget in same page
Json
List<dynamic> forms = [
{
"id": 65,
"label": "Is this a test drive period or demonstration period?",
"code": "survey_general",
"type": "select_box",
"service_id": 48,
"client_type": "SURVEY_MITSU",
"column_order": 1,
"required": true,
"options": {
"step_number": "1",
"step_label": "General Information",
"options": []
},
"validation": null,
"requisite": false,
"multiple": false
},
]
Title
Container(
margin: EdgeInsets.fromLTRB(16, 20, 16, 8),
child: Text(
'Part 1: ${jsonEncode(forms['options']['step_label'])}',
style: Constants.textTitle.copyWith(
fontSize: 16,
fontFamily: 'Nunito',
),
),
),
It is not an appropriate approach to access the variables from other Widgets. The forms variable is not a local variable in Title.
There are two approaches:
Put the dummy variable forms into the Title Widget
Create a new class to store your dummy variable
class Dummy{
static const List<dynamic> forms = [
{
"id": 65,
"label": "Is this a test drive period or demonstration period?",
"code": "survey_general",
"type": "select_box",
"service_id": 48,
"client_type": "SURVEY_MITSU",
"column_order": 1,
"required": true,
"options": {
"step_number": "1",
"step_label": "General Information",
"options": []
},
"validation": null,
"requisite": false,
"multiple": false
},
];
}
Container(
margin: EdgeInsets.fromLTRB(16, 20, 16, 8),
child: Text(
'Part 1: ${jsonEncode(Dummy.forms['options']['step_label'])}',
style: Constants.textTitle.copyWith(
fontSize: 16,
fontFamily: 'Nunito',
),
),
),

The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't in Text widget

I am trying to display the name and email of the person when he logs in to the profile screen using Getx
Column(
children: [
Text(
controller.userModel!.name,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Kprimarycolor,
),
),
Text(
controller.userModel!.email,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Kprimarycolor,
),
),
],
),
],
but this error keep showing Error in vs code
and Error in terminal
the related code to name and email is
class UserModel {
late String? userId, email, name, pic;
UserModel({
required this.userId,
required this.email,
required this.name,
required this.pic,
});
UserModel.fromJson(Map<dynamic, dynamic> map) {
userId = map['userId'];
email = map['email'];
name = map['name'];
pic = map['pic'];
}
toJson() {
return {
'userId': userId,
'email': email,
'name': name,
'pic': pic,
};
}
}
I tried to add .toString() and as String but the error keeps showing after debugging
Column(
children: [
Text(
controller.userModel!.name!,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Kprimarycolor,
),
),
Text(
controller.userModel!.email!,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w600,
color: Kprimarycolor,
),
),
],
),
],
I added '!' character, it should work.
In your model, late String? userId, email, name, pic; and #Salih Can answer will be work.
Here, String? means string can accept null value. But Text widget don't accept null value. You need to use bang operator ! to handle it and by adding ! means this value is not null anymore. A better practice would be checking if it is null or not, then assign on Text. It can be
Text(myVal==null? "defalut value": myVal)
Text(myVal??"default Value")
if(myval!=null) Text(myVal) and it will render only if string is not null.

Flutter apply condition on text widget if data isnt available

I am showing data in text widget like this
Text(
posts[position]['OrderDetailModifiers'][0]['ModifierName'].toString() ?? 'N/A',
style: TextStyle(
fontFamily: 'SFPROBOLD',
fontSize: 13, color: Colors.grey),
),
Issue is some time posts[position]['OrderDetailModifiers'] is null
right now its look like this
"OrderDetailModifiers": [
{
"ModifierName": "Single",
}
]
But some time its look like
"OrderDetailModifiers": [
]
Need to know how can I apply condition in my text widget if its null or not available so don't show text widget.
You can make if statement in your widget tree.
if (posts[position]['OrderDetailModifiers'].isNotEmpty)
Text(
posts[position]['OrderDetailModifiers'][0]['ModifierName'].toString(),
...
),
You can simply check the length and then show
Text(
posts[position]['OrderDetailModifiers'].length>0?posts[position]['OrderDetailModifiers'][0]['ModifierName'].toString(): 'N/A',
style: TextStyle(
fontFamily: 'SFPROBOLD',
fontSize: 13, color: Colors.grey),
),
Try using null-aware operators like this:
void main() {
printFirstModifierName(data); // Azerty
printFirstModifierName([]); // N/A
printFirstModifierName(null); // N/A
}
void printFirstModifierName(List<Map<String, dynamic>> data) {
print((data?.firstOrNull ?? const {})['ModifierName']?.toString() ?? 'N/A');
}
extension ListX<T> on List<T> {
T get firstOrNull => isEmpty ? null : first;
}
final data = [
{ 'ModifierName': 'Azerty' },
{ 'ModifierName': 'Qwerty' },
{ 'ModifierName': 'Tyuiop' },
];

Variable value gets null outside setState() in Flutter

TextField(
style: TextStyle(
fontFamily: "Averta",
fontWeight: FontWeight.bold,
fontSize: 16,
color: Colors.black),
enableSuggestions: true,
onChanged: (value) {
setState(() {
final title = value;
print(title);
});
},
decoration: InputDecoration(
border: InputBorder.none,
contentPadding:
EdgeInsets.all(18),
hintText: "Enter Task Title",
hintStyle: TextStyle(
fontFamily: "Averta",
fontWeight: FontWeight.normal,
fontSize: 12,
color: Colors.grey.shade300),
),
),
Here,I have a title variable which I update with onChanged() function.
Here the print() function shows exact change in value which I do in TextField.
But I don't want to pass it here, I want to take some more data and then pass it when I click the CREATE button here-
InkWell(
onTap: () {
print(title);
setState(() {
DatabaseHelper _dbhelper =
DatabaseHelper();
Task _newTask = Task(
title: title,
year: year,
month: month,
day: daye,
hour: hour,
minute: minute,
weekday: weekday);
_dbhelper
.insertTask(_newTask);
});
}
Here the print statement shows "null",but I want to use the value which was updated above in TextField.
How can I achieve this in Flutter?
This line creates a new variable called title and sets it:
final title = value;
You want to access the already existing variable:
title = value;
That should work.