Pass empty map as arguments Getx - flutter-getx

For some reason I want to pass company model as empty object in Get.toNamed argument. I tried this way
Get.toNamed("/profile?id=${data.id}", arguments: <Company>{})
received like this :
Company company = Get.arguments;
But I got this error
Set<Company>' is not a subtype of type 'Company'

To pass an empty object you need to use .empty :
Navigator.pushNamed(context, "/profile", arguments: Company(id: null, name: null, etc: null));
I hope this helps.

Related

DART: attribute of attribute of class

I have a classmodel in dart with a json mapper like
class DA_Field {
final String strGROUP;
DA_Field({
required this.strGROUP, });
static DA_Field fromJson(json) => DA_Field(
strGROUP: json['GROUP'] as String, );
}
and I want to set a attribute of the attribute strGROUP via a function - so that I can call that sub-attribute 'width' for example by:
intWidth = DA_Field.strGROUP.width
My first attempt was to create a setter - but after a lot of google, I only get in touch to create a setter for the whole modelclass, not for all of the single attributes.
The values should be calculated by a function outside of the class - I thought maybe this could be possible by .forEach function - like ?
DA_Field.forEach((k,v) => k.width = functionxx(k));
But i get following errors:
error: The setter 'width' isn't defined for the type 'DA_Field'. (undefined_setter...)
error: The argument type 'void Function(DA_Field, dynamic)' can't be assigned to the parameter type 'void Function(DA_Field)'. (argument_type_not_assignable)
Can anyone give me a suggestion on how to do that?
Thanks..

The argument type 'String?' can't be assigned to the parameter type 'String' in flutter for shared prefrances

so I am using shared preferences in a flutter app and I get this error :
The argument type 'String?' can't be assigned to the parameter type 'String'
and here is the code:
if (result != null) {
SharedPreferenceHelper().saveUserEmail(userDetails.email);
}
the error is userDetils.email can someone pls help
A picture of what it shows
Those are two different types. You need to coerce String? to String either by the null coercion operator: userDetails.email! or by giving it a default value if it's null: userDetails.email ?? ''
After looking into the image posted the line 30 declaration states that:
User? userDetails = result.user;// Which potentially means that variable userDetails could be null
Where as the class User details are not shared but peaking into the issue I am pretty sure the class User has a email parameter whose declaration is as includes it's datatype as String? email something like this with prefix of final or late.
In this case what happens is that you have nested level of nullity for accessing email variable out of userDetails object.
Which means:
Case 1=> userDetails is null and email is null.
Case 2=> userDetails is not null and email is null.
Case 3=> userDetails is not null and email is not null.
Meaning both `userDetails` and `email` have a datatype of which defines them to be null at compile time.
Since dart is statically typed language so you need to add in ! after each variable whose datatype is nullable at compile time to allow dart know that the variable has data in it and was assigned a value sometime later in run time.
So to fix this what you need to do is that replace the line below with line 33:
SharedPreferenceHelper().saveUserEmail(userdetails!.email ?? "Some default email");
// if you never want to save null as email pref else use the one below
SharedPreferenceHelper().saveUserEmail(userdetails!.email.toString());
It is sound null safety problem
String? means Whatever variable assigned to Stirng? type it can be null or null value is available
,so make sure to check it null or not by providing userDetils.email?? this means userDetils.email is null or not

How to deal with information that arrives null? - NoSuchMethodError

I'm getting null information from a web api. If a single information is null, the error will occur:
Error: Exception: NoSuchMethodError: '[]'
Dynamic call of null.
Receiver: null
Arguments: ["address"]
I declared this information in the model like this:
final String? address;
..
address: json['data1']['data2'][0]['data3']['address'][0]
I tried to do something like:
address: json['data1']['data2'][0]['data3']['address'][0].isEmpty
? ''
: json['data1']['data2'][0]['data3']['address'][0],
But it does not work.
I appreciate if anyone can help me analyze it!
The only thing you can do is to anticipate the null values and handle each case as needed.
For instance, if a null value is not accepted at all, you could wrap the code in throw ... catch statement then throw an error -- e.g.Missing Data and handle that error.
If having a null value is fine, you can use the null aware operator ? (or a nested if-statements if you prefer that). For example, assuming the value is a String, you could do something like this:
final String? myValue = json['data1']?['data2']?[0]?['data3']?['address']?[0];
Though, keep in mind if you're accessing a list by index, you still can get a RangeError if the index is out of range or if the list is empty. In such case you may need to split the process in a separate method and inspect each part separately such as:
String? extractValue(Map<String, dynamic> json) {
final firstList = json['data1']?['data2'];
if (firstList is List && firstList.isNotEmpty) {
final innerList = firstList[0]['data3']?['address'];
if (innerList is List && innerList.isNotEmpty) {
return innerList[0];
}
}
return null; // or return a default value or throw an error
}
You can handle such arguments ( arguments that give you null value) like this.
Let's say there's a variable a and there's a possibility that it'll give a null value, you can give it a default value.
For example:
There is a variable 'a', which is your data source.
String name = a ?? "This is not a null value";
The ?? would check if the value is null or not. If it's null, it would assign the value that you provided, otherwise it would keep the existing one.

A value of type 'List<Customer>' can't be assigned to a variable of type 'Future<List<Customer>>'

How to convert 'List' to 'Future<List>'. I need get two type ('List' & 'Future<List>' ) in different places
My api response
var data = jsonDecode(r.body);
custList.add(new Customer(
data[i]['CustomerID'],
'${data[i]['ProfileImageUrl']}' + '${data[i]['ProfileImage']}',
'${data[i]['CompanyName']}',
data[i]['Email'],
data[i]['RegisterNumber'],
data[i]['PhoneNumber'],
data[i]['BillingStreet'],
data[i]['BillingCity'],
data[i]['BillingZip'],
data[i]['MasterCountryName'],
data[i]['MasterStateName'],
data[i]['Type'],
new customeraddress(data[i]['BillingStreet'],
data[i]['BillingCity'], data[i]['BillingZip']),
status,
data[i]['CustomerTaxExemptType'],
data[i]['MasterCountryID'],
data[i]['MasterStateID'],
));
How to convert 'List' to 'Future<List>'.
If you are not entirely sure if you get a T or a Future<T>, you can use the FutureOr<T> (documentation) class.
To create a Future<T> from a value to satisfy some compiler syntax, you can use the named constructor Future.value (documentation).
For more information on Futures: What is a Future and how do I use it?

How do I conditionally pass argument to Widget in Flutter/Dart?

I want to conditionally pass an argument while using the widget. Is there any way to do so?
...
return ListTile(
title: Text("${product.name}"),
// want to conditionally pass subtitle, which is not the right syntax (???)
if(condition) subtitle: Text("subtitle"),
// I know about this
subtitle: condition? Text("subtitle"): null,
);
},
...
I know we can conditionally pass the value as null using ternary operator here but what I am looking for is to skip the argument itself.
The above example is for ListTile widget. But my curiosity is to know the syntax for doing so for any widget.
Using optional named parameters, using parameter:value when a parameter is required pass its value else it can be skipped completely. Inside the called method null handling is required to be done by the developer(not handled internally).
This is a simplified sample:
void main() {
doNothing();
doNothing(index: 1);
doNothing(description: 'Printing');
doNothing(index: 1,description: 'Printing');
}
void doNothing({int index, String description}) {
print('Received => $index : $description');
}
Output:
Received => null : null
Received => 1 : null
Received => null : Printing
Received => 1 : Printing
Note: Default values can be assigned in the Widget/methods implementation and may not necessarily be always null.
Example:
void doNothing({int index, String description, String otherDesc = 'Provided By Default'}) {
print('Received => $index : $description : $otherDesc ');
}
Output:
Received => null : null : Provided By Default
Since not explicitly initialized variables in dart get automatically initialized to null (if they don't have a default value), for the widget there is no difference between not giving an argument to the optional parameter and giving the argument null.
Because of that setting it to null is actually skipping the argument. I would recommend just using the ternary operator in case you don't want to give an argument.