Using a future object's data in a flutter list - list

#override
void initState() {
super.initState();
futureInfo = fetchInfo();
}
Future<Info> futureInfo;
List<String> prices = [];
List<String> duration = ["11 hours", "14 hours", "15 hours","12 hours", "10 hours", "8 hours",];
List<String> airline = ["Middle East Airline", "Air Canada Airline", "Turkish Airline","Middle east Airline", "Turkish Airline", "Air Canada Airline",];
List<String> destination = ['Beirut','Madrid'];
Hello
I am still very new to flutter and I just wanted to know how can I use the data in the future object futureInfo in the list of prices where futureInfo is a parsed Json file into a class I have and I wanna be able to access it's attributes.
Also could you refer me to any documentations or videos that might help me learn the more technical part of flutter/dart not the more UI things.(ex: functions, states, variables ...)

For understanding of future you should to go through this: https://dart.dev/codelabs/async-await
If you are very new then I would like to suggest you to go through this for Http call: https://flutter.dev/docs/cookbook/networking/fetch-data
Otherwise I would ask you to follow Bloc library for a lil deep knowledge to handle State changes. Bloc library is here: https://bloclibrary.dev/

I recommend you put info object
Info info;
instead of
Future futureInfo;
, then make your fetchInfo() method asynchronous like this,
fetchInfo()async{
//inside async method you can wait for any future to complete using await keywork
await operation1;
await operation2;
//then setState your Info object
setState(() {
this.info = newValue;
});
}
Please it is easier if you post your full code for more clarity.

Related

In Kotlin, how can one unit test that a data class, sealed class, or class field are not changed?

Basically we might have some data like so
open class RealmCart : RealmObject() {
#PrimaryKey
var _id: String = UUID.randomUUID().toString()
var items: RealmList<RealmCartItem> = RealmList()
var discountCode: String? = null
var userId: String = ""
}
And we do not want people editing these by mistake. We have some failsafe like code owners, labels in the repo, but we also want to have a unit test that can also prevent a merge if the data is changed in any way (add, change, or remove data). Basically, we do not want any accidents, and people are not perfect.
What is the best way to go about such a thing?
This is what I ended up doing:
I created an extension function for my data models
fun RealmObject.testDeclaredFields(): List<String> {
val fields = this::class.java.fields.map { it.name }
return this::class.java.declaredFields
.map { it.name }
.filterNot { fields.contains(it) }
.sorted()
}
Basically this just gets the data model fields, excluding things like companion objects.
Then I was able to create a test simply like
class RealmMessageTest {
#Test
fun `RealmMessage fields match spec`() {
val item = RealmMessage().testDeclaredFields()
assertContentEquals(item, fieldSpec)
}
private val fieldSpec = listOf(
"_id",
"acknowledgeStatusValue",
"body",
"completed",
"createdAt",
"deliveryStatusValue",
"from",
"meta",
"organizationId",
"platforms",
"threadId",
"title"
).sorted()
}
Why do this? Sometimes when someone is making changes carelessly, they will not realize that they have added a field, changed a field, or removed an important field in a data model that is sync'd to the backend. This does not prevent the developer from changing it, but given that they need to now change it in two places, they will be more cognizant whether they need to make this change or not.
I noticed a lot of people questioned why you would need to do this. My answer is that, I work in a very large repo where newer developers edit this without a second thought. This is just to make them more cognizant of changes to these important models, before they break develop. There are code owners for the repo, but they may not always see these changes. It is just an extra precaution.
How about using a mechanism like githooks to prevent the editing of certain files from being committed?
I'm not familiar with githooks, so I can't show you exactly how to do it, but I think it would be good to prevent commits and inform the developer of the situation with an error message.

How to get street name from postcode using maps API?

I'm looking for solution to change post code e.g DD3 7BN, but not using geo position. I found one solution using url http://maps.googleapis.com/maps/api/geocode/json?address=DD37bn.
One guy was provide another solution but its not work for me.
But it shows error GRPS Failed. What is the best solution for my problem?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getAddressByPostalCode("");
}
public void getAddressByPostalCode(String val_pcode) {
Geocoder geocoder = new Geocoder(this.getApplicationContext(), Locale.getDefault());
try {
List<Address> addresses1 = geocoder.getFromLocationName (val_pcode, 1);
Address obj1 = addresses1.get(0);
List<Address> addresses = geocoder.getFromLocation(obj1.getLatitude(), obj1.getLongitude(), 1);
Address obj = addresses.get(0);
/*TextView street = (TextView)findViewById(R.id.editText1);
TextView pcode = (TextView)findViewById(R.id.editText2);
TextView blk = (TextView)findViewById(R.id.editText3);
TextView build = (TextView)findViewById(R.id.editText4);
street.setText(obj.getThoroughfare());
pcode.setText(obj.getPostalCode());
blk.setText(obj.getSubThoroughfare());
build.setText(obj.getPremises());*/
} catch (IOException e) {
Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
Be aware that UK postcodes don't always relate to single street, HD7 5UZ covers 7 and as a result google API doesn't return the "route" element - http://maps.googleapis.com/maps/api/geocode/json?address=HD75UZ
I don't think there are any open datasets that offer the link between postcode and street, there are ones that have a complete list of streets or postcodes along with other geo data though.
Another solution for the UK is to use an API that looks at the Royal Mail PAF dataset, this will have linkage between postcodes and the streets they relate to. This will come with a cost however typically if you are after only the street name, not premise level data the cost is quite low.
An example would be the "street" endpoint from Allies Computing (who I work for) which will return an array of the streets. Which you can either get the user to select the right one or if there is only one, auto select it for them.
Most other PAF resellers also offer a street level search and they can be found via the Powered by PAF website.

Accessing storage synchronously with ionic 2 storage service

One of the recurring problems i've been having with ionic 2 is it's storage service. I have successfully set and retrieved stored data. However, when i store something, it is inaccessible on other pages unless i refresh the page/application.
Example one: Editing a contact
I push to an edit contact page, make changes, then saveEdits. saveEdits successfully makes the change to the right contact but fails to update the contact list UNTIL the application is refreshed.
HTML:
<button (click)="saveEdits(newName, newPostCode)"ion-button round>Save Edits</button>
TypeScript:
saveEdits(newName, newPostCode){
console.log("saveid"+this.id);
this.name = newName; //saves property
this.postcode = newPostCode; //saves property
this.items[this.id] = {"id": this.id, "Name": newName, "PostCode": newPostCode};
this.storage.set('myStore',this.items);
//this.navCtrl.pop(ContactPage);
}
Example two: Accessing contacts on another page
On another page i iterate through contacts and display them in a radio alert box list. Again, the contacts are displayed successfully, but when I add a contact on the add contact page, the new contact does not appear on the radio alert box list.
addDests(){
console.log('adddests');
{
let alert = this.alertCtrl.create();
alert.setTitle('Choose Friend');
for(let i = 0; i<this.items.length; i++){
console.log('hello');
alert.addInput({
type: 'radio',
label: this.items[i].Name,
value: this.items[i].PostCode,
checked: false
});
}
alert.addButton('Cancel');
alert.addButton({
text: 'OK',
handler: data => {
console.log(data);
}
});
alert.present();
}
}
You're changing the reference the variable is pointing to:
this.items[this.id] = {"id": this.id, "Name": newName, "PostCode": newPostCode};
I assume that your LIST is iterating (ngFor) over the array referenced by this.items? If yes, update directly the properties of this.items[this.id] instead of re-initializing it.
this.items[this.id].Name = newName;
this.items[this.id].PostCode = newPostCode;
(By the way, I'd recommend to be consistent with your property naming: either Id and Name, or id and name (capital letters matter!)).
Your "list" view will always be refreshed if the references to the objects being used are not changed. The only exception would be an update made in a callback given to a third-part library. In that case, you can use NgZone to "force" Angular to take the update into account.
Also, have a look at Alexander's great advice about Observable.
You should use Angular provider(s) with Observable property to notify subscribers (other pages & components) about changes.
For example read this article: http://blog.angular-university.io/how-to-build-angular2-apps-using-rxjs-observable-data-services-pitfalls-to-avoid/
There are a lot of information on this: https://www.google.com/search?q=angular+provider+observable

IBM Watson Alchemy news iOS SDK Swift

The IBM Watson iOS SDK using the Alchemy News service on Bluemix returns a string result which requires parsing to pull out the fields like url and cleaned title. ref: https://github.com/watson-developer-cloud/swift-sdk
I pull the string into an array and parse it in swift3 using some string methods but this is pretty ordinary and can produce unpredictable results
Is there a more elegant approach where I can access specific fields, like the url and cleaned title which I am passing to a UITableViewCell to select and segue to the url link.
sample code:
let alchemyDataNews = AlchemyDataNews(apiKey: apiKey)
let failure = { (error: Error) in print(error) }
let start = "now-14d" // 7 day ago
let end = "now" // today
let query = ["count": "15",
"dedup": "true",
"q.enriched.url.title": "[IBM]",
"return": "enriched.url.url,enriched.url.title" "enriched.url.title,enriched.url.entities.entity.text,enriched.url.entities.entity.type"]
Also I have noticed the search string [IBM] has a prefix of 0, i.e. 0[IBM] and have also seen an "A". What do these prefixes mean and where are they documented
Here is one way you can access the fields from a returned payload.
alchemyDataNews.getNews(from: "now-4d", to: "now", query: queryDict, failure: failWithError) { news in
for doc in (news.result?.docs)! {
var cleanedTitle = doc.source?.enriched?.url?.cleanedTitle
var author = doc.source?.enriched?.url?.author
var title = doc.source?.enriched?.url?.title
}}
Also, here is a nice API reference link for alchemy data which contains all of the request parameters and filters.
https://www.ibm.com/watson/developercloud/alchemydata-news/api/v1/

Subsonic 3 ActiveRecord Setup() behavior

Been a long time user of Subsonic 2.x and have used 3.x a bit, but I've recently started transitioning our use of SS from using repositories to ActiveRecord instead. I'm currently stumbling on some of our unit tests and I wonder if it's perhaps because I'm misunderstanding the intent of the Setup() method. Alas, the only documentation I can find is on Rob Conery's blog.
On my unit tests, I'm stuffing a collection of objects, let's say a List of Accounts. I then want to validate that some code is properly filtering against the repo by a property, let's say the email address. My (simplified) unit test setup is below.
The kicker is that when using the "Test" connection strings, it seems like any LINQ I write against the repo returns me all the records I stuffed into the Setup--which is making me wonder if I'm misunderstanding the intention of Setup(). It's as if it were behaving like a Mock setup, e.g. mymock.Setup(foo => foo.Email).Returns("user#user.com").
List accounts = new List()
{
new Account() { FirstName = "Paul", LastName = "McCartney", Email = "paul#beatles.com" },
new Account() { FirstName = "John", LastName = "Lennon", Email = "john#beatles.com" },
new Account() { FirstName = "Ringo", LastName = "Starr", Email = "ringo#beatles.com" },
new Account() { FirstName = "George", LastName = "Harrison", Email = "george#beatles.com" },
new Account() { FirstName = "Taylor", LastName = "Swift", Email = "immaletyou#finish.com" }
};
DB.Account.ResetTestRepo();
DB.Account.Setup( accounts );
Elsewhere, the code I'm trying to unit test is basically performing a Find(). The real implementation has a semi complex set of conditions, but even simplified conditions don't appear to work.
Account.Find(a => a.Email == "immaletyou#finish.com").SingleOrDefault();
The above will bomb with an exception indicating that the lambda returned multiple elements. When I debug into the test, sure enough, the result of the Find() is all the objects I had stuffed into the mocked repo via the Setup() method.
Rob C laments that ActiveRecord can be tough to test--which is a bummer. But I can't imagine that the testing scenario is breaking on such a mundane sample--it's PEBKAC right?
Halp!?
Edit:
Josh Rivers asks what appears to be a similar question, though it doesn't appear to be resolved. Linking for completeness.
Going to answer my own question for any future parties, not that there's a ground swell of activity rushing to this thread:
Turns out that the current implementation of test repositories (Subsonic 3.03) has a bug where it basically just returns the entire set of values inside the repository. The current fix (haven't tested myself, but has worked for others) is to pull the current main line of the source code and recompile.
See: Subsonic Issue 109