Saving arrays on Flutter - flutter

I have an array that contains widgets List<ListCard> listsList= []; And inside each widget I have an array that has objects of a class called Product List<Product> products = [];. Through the app you can add products to the list but I want to save this 2 arrays (and the inner objects). How can I do it? I thought I can do a database but maybe there is something more straightforward than designing all the schema.

You can use this package https://pub.dev/packages/localstorage . It is pretty straighforward

There are two ways to this:
1) Use this package, it's pretty simple to use and doesn't require you to write anything super complex. One downside - data is saved on the device, so if the app is deleted - all information is lost.
2) Attach Firebase Storage, using official packages. Installation of it is not complex at all, though you will need to convert your Product to Map
Both methods are valid and pretty fast to implement without groundbreaking changes.
If any questions occur - feel free to ask :3

Related

How to build complex relationships in CoreData correctly?

I am dealing with CoreData, for training, I decided to create a small application for recording user income and expenses. CoreData tutorials all contain To-Do-List examples, and I haven't found any good examples that would help me.
// MARK: - Grammar
// I want to apologize for grammatical errors in the text. Unfortunately,
// English is not my native language, so in some places I used a translator.
If something is not clear, I will definitely try to explain it again.
When I began to think over how I would implement the application, I assumed that the most convenient way would be to save all user operations and make calculations in the application in the right places. So far, abstract, since It seems to me that this has little to do with the question, if you need to be more precise, I can provide a complete idea.
So, I'm going to save the user model, which will have the following data:
User operations (Operation type) - all operations will be saved, each operation includes the category for which the operation was performed, as well as the amount in currency.
User-selected categories (Category Type) - Categories that will be used for expenses or income when adding an operation.
Wallets (Type Wallet) - User's wallets, Everything is simple, the name, and the balance on it.
Budget Units (BudgetUnit Type) - These are user budgets, contains a category, and a budget for it. For example: Products - 10.000 $
When I started building dependencies in CoreData, I got a little strange behavior.
That is, the user has a relationship on the same category model as the Budget Unit and Operation. Something tells me that it won't work that way.
I want the user categories to be independent, he selected them, and I'm going to display them on the main screen, and each operation will have its own category model
In the picture above, the category model is used 3 times, the same model.
This is roughly how I represent the data structure that I would like to see. Different models have their own category model, independently of the others.
I think it could be implemented using 3 different models with the same values, but it seems to me that this approach is considered wrong.
So how do you properly implement the data model so that everything works as expected? I would be grateful for any help!
--- EDIT ---
As a solution to the problem, I can create multiple entities as Category (Example bellow)
But I don't know if this is good practice
I looked into several other open source projects and saw a solution to the problem.
I hope this helps someone in the future.
There is no need to save the categories for the user, you can simply save the categories in the application by adding the IsSelected and ID parameter to them in order to change these parameters when you select a category, and immediately understand which ones you need to display.
For budgets and operations (transactions) , we only need to save the category ID to immediately display the correct one.
For example:
Thanks #JoakimDanielson and #Moose for helping. It gave me a different view of the subject.

Immutable vs Observable collections in Flutter

When using Flutter with realtime databases, such as Firebase Database, it is beneficial to know not just that a collection has been updated, but where exactly. Such as to show a pretty list animation, or trigger some additional events based on which item has updated. Dart already has an amazing infrastructure for delivering events.
A canonical example is to use a FirebaseAnimatedList, but it's glued to Firebase and doesn't support filtering and ordering (outside of very basic Firebase model). I am looking for a more generic solution, which would allow to inject some logic between database (that notifies of item change/insert/delete), and aforementioned AnimatedList, which expects the same events.
Most recent tendency seems to be in favor of immutable collections, such as built_value, which makes a lot of sense in Dart, as object creation is very cheap. However, immutable collections do not have a way of telling which item has changed, they simply deliver a new collection. This approach also makes it difficult to attach some local information to an item, such as "selected" bit when user multi-selects items, or custom ordering. Because, well, items are immutable, and their reference (aka pointer, aka object ID) keeps changing.
One alternative solution is to implement a kind of observable list, such as what package:observable offers, but it seems that its authors are not convinced of its popularity anymore. So what is the approach you take to create animated, filtered, sorted, selection-supporting lists in Flutter, backed by a realtime database?
However, immutable collections do not have a way of telling which item has changed, they simply deliver a new collection.
Some pseudo code: (old collection) - (new collection) = (what changed) - works the other way around too.
This approach also makes it difficult to attach some local information to an item, such as "selected" bit when user multi-selects items, or custom ordering.
Extend said 'item' and add a property selected (or order, or any other info you want available), then just construct the new list with these properties properly set.
There are a lot of state-management-with-Flutter-related questions around these days, so to avoid repeating myself, I would rather link you to an answer of mine from earlier today.
Edit:
I just want to insert a practical example regarding (old collection) - (new collection) = (what changed):
Basically this is how to see what changed when comparing 2 lists, containing closely related elements.
List currentState = [...];
List nextState = [...];
List addedItems = nextState.where((e) => !currentState.contains(e)).toList(),
List removedItems = currentState.where((e) => !nextState.contains(e)).toList();
doSomethingWith(addedItems);
doSomethingElseWith(removedItems);
Of course you should keep in mind that the Lists should be deeply comparable, i.e. for Dart's specific case you can use built_value or equatable packages.
I have also uploaded a repository, with a pure Dart project example. You're more than welcome to do whatever you want with the code.

information duplication with nosql?

I'm using Redis as nosql database (and really enjoying it) but there are some cases where it's not the more handy (I know that not every data model can be used with nosql, but still...).
I'd like to know if there is a proper way to perform the following in Redis or if I definitively need to go for a RDMS instead.
Let's say I have 2 objets:
- User
- Asset
an Asset can be either a "flat", a "building" or a "house".
I use a redis list named "assets" that gathers the assets like:
assets = [asset:1, asset:2, ....]
Each assets is a hash like:
asset:1 = {type: flat, value: 150000$}
How can I get the list of all the assets of type "flat" ?
The easiest way would be to iterate through the list of assets and check the type of each one, that's linear so that's seems quite good.
Is there a better solution ?
It could be usefull to have a new list: "flats" that would contains the references of the assets with type "flat" but this news list would cause an overhead as we will need to be sure it's synchronized.
flats = [asset:1, asset:5, ...]
But this lead to data replication... which is bad... Is this still the way to go with nosql ?
Any other suggestions ?
I usually build a second key that contains an index. So, when you write a new asset, you write it to your set of assets and to your set of specific asset types. It's overhead, but it's the same overhead you'd experience in other databases, it's just up front. Indexing always requires an additional write, Redis just makes it really obvious that this is happening.
Also, I would just store the id in your "assets" set, rather than asset:1, just store 1

ios5 core data or pref list

q) what is the best method of storing persons complete details i.e.
steve > details contain :name address,dob, other details etc..
john > details contain :name address,dob, other details etc..
and many more records max would be around 200 tops.
now i want to display these individually and with the option to add them what is the suggested way?
i had a look at core data,userdefaults and NSFileManager but not sure what would be best way to implement such nested texts for save and load.
if you want to search or query them I would always recommend going with core data from the get go.
You'll only end up wishing you add gone down that route in a few months and then would have to factor in a migration.
For core data I use https://github.com/magicalpanda/MagicalRecord for new projects, it does most of the heavy lifting for you.
For a recent app I used NSUserDefaults. Basically keeping all my 'person' objects as NSDictionaries in an NSArray. This suited the app as the data was low, c100 records in use max.
I could just as easily have used a save to disk method, but as I did't have any other use for saving small amounts of preference data, it was just a convenience.
(remember, accessing NSUserDefaults brings back all its contents, not just the particular object you are interested in).
Hope this helps.

Aggregate Pattern and Performance Issues

I have read about the Aggregate Pattern but I'm confused about something here. The pattern states that all the objects belonging to the aggregate should be accessed via the Aggregate Root, and not directly.
And I'm assuming that is the reason why they say you should have a single Repository per Aggregate.
But I think this adds a noticeable overhead to the application. For example, in a typical Web-based application, what if I want to get an object belonging to an aggregate (which is NOT the aggregate root)? I'll have to call Repository.GetAggregateRootObject(), which loads the aggregate root and all its child objects, and then iterate through the child objects to find the one I'm looking for. In other words, I'm loading lots of data and throwing them out except the particular object I'm looking for.
Is there something I'm missing here?
PS: I know some of you may suggest that we can improve performance with Lazy Loading. But that's not what I'm asking here... The aggregate pattern requires that all objects belonging to the aggregate be loaded together, so we can enforce business rules.
I'm not sure where you read about this "Aggregate Pattern". Please post a link.
One thing it could be is where we encapsulate a list into another object. For a simple example if we have a shopping cart instead of passing around a list of purchases we use a cart object instead. Then code that works on the whole cart (eg. getting total spend) can be encapsulated in the cart. I'm not sure if this is really a pattern but google found this link: http://perldesignpatterns.com/?AggregatePattern
I suspect when you say
"The aggregate pattern requires that
all objects belonging to the aggregate
be loaded together, so we can enforce
business rules. "
this depends on your business rules.
Generally patterns should not be regarded as a set of rules you must follow for everything. It is up to you as a developer to recognise where they can be used effectively.
In our cart example we would generally want to work on the whole cart at once. We might have business rules that say our customers can only order a limited about of items - or maybe they get a discount for order multiple items. So it makes sense to read the whole thing.
If you take a different example eg. products. You could still have a products repository but you needn't not load them all at once. You probably only ever want a page of products at a time.