How do I use an enum in Flutter to define names for selectedIndex that synchs with destinations - flutter

I'd like to define an enum (or something) to give names to possible values of seletedIndex and define the order of destinations in, say, a Flutter NavigationBar in such a way that I only have to go to one place to change the order of the destinations.
The examples I've seen so far always require reordering be done in two places: one in the list of destinations given to the NavigationBar that have an implicit, invisible, unnamed index, and the other is a switch or a subscripting based on selectedIndex to establish the selected page. This seems like a bug magnet. Is there any way to set it up so I only define the order of the destinations in one place and have the list of destinations bound to the correct pages?
It seems to me that NavigationDestination should have a property to handle this binding or a "displayOrder" property, but I don't see this. If there isn't a better way, I guess I could write a function to construct the destination list based on an object (like an enum) that binds the numeric indicies to the corresponding page view, but this seems like a lot of machinery to create for a routine navbar task, especially in this modern OO context -- weird that selecting navbar pages would need a switch in the switchless programming world. Yet the example implementations have switches and two separate areas of the code need to be maintained to do one thing. But, what do I know; obligatory newbie disclaimer follows...

I think my question above was poorly phrased, based on ignorance and seeing some naive examples that suggested page navigation was generally done with an integer like selectedIndex. Once I learned about the Navigator class, and other navigation and List related builders, I saw the OO techniques Flutter provides for putting together hierarchical menus and such without the use of switch statements and integer indicies. So my answer to somebody like me who asks "do I really need to re-invent the navigation wheel" is to learn about Navigation Basics first.

Related

Swift - Which trait collection to use?

There are a ton of ways that I found to get the current userInterfaceStyle, but I can't tell what is the most appropriate method of getting it.
There are four ways that I found:
UITraitCollection.current.userInterfaceStyle
UIScreen.main.traitCollection.userInterfaceStyle
UIApplication.shared.keyWindow?.traitCollection.userInterfaceStyle
traitCollection.userInterfaceStyle
I generally used number 4 whenever I had to make a global function, and just had the trait collection as a parameter. Doing that seems unnecessary, though. There should be a universal variable. Which of these should we be using?
UITraitCollection.current is a special call that is used in order to get the interface style when you're in a graphics drawing situation. So it isn't really related to the other three.
As for those three, there can be different trait collections / user interface styles at different levels of the hierarchy, and there are different ways to refer to the various objects that comprise the hierarchy. So I can think of a dozen more ways to get the trait collection! But when you want to know the trait collection, you should just ask for the one at the level of the hierarchy you are interested in. Usually this will be the one closest to where your code is. For example, if this is view controller code or view code, you will usually ask for self.traitCollection.

How do you organize your UI design variables, objects, etc. in iOS?

As the iPad app I am making has been growing its size, it is hard for me to keep track of UI design values. Here, I am talking about values such as a table's width, background colors, and a title's font.
I would like to organize all UI design-related values and objects more efficiently.
How do you organize these?
Do you #define values in a header file?
Do you declare them as global variables or not?
Do you put your values one static class?
Or do you think not-organizing these values is rather better?
I would like to hear your advice.
Thank you :)
Yes it depends, therefore just some rules of thumb...
Do you #define values in a header file?
...in cases where I might want to change this locally only, eg for constants, colors, alignments, button images, ... the main reason why I do this however is the documentation it allows by giving the local defines a long explaining name
Do you declare them as global variables or not?
...an all my apps I have a MainDataManager Class, that holds all the variables I need globally - for the UI part often I have my own globally used object. This is extremely useful, simplifies the code, and probably one of the most important things I learned early on. might also see here Using Variable of AppDelegate as a Global Variable - question regarding release/retain
Do you put your values one static class?
...static classes exist kind of conceptually. Static variables are quite useful when you want to give a method some kind of memory of its own. However, none plays an important role in my UI.
In general, I like to use IB to layout the screens but set all the button names, labels, texts in the code. Why? Because when I have to localize the app maintaining multiple XIB files (for each language there will be one isolated XIB file to maintain) becomes a real burden even if there is only one single change in the layout.
All the global constant settings are always kept in GloblDefinitions.h while at the same time I have in my .pch file this entry #import "GlobalDefinitions.h"
So the combintation of a delegate variable provided globally + GlobalDefinitions.h for constants is my solution.
Its a good question. When combining use of interface builder with hand-coded UI tweaks and/or custom components you also have the problem of duplicated values between IB and code.
In some situations, for readability and for easy adjustment by a third party its easier if values are just hard coded in-place - so in trival cases (e.g. cases where the value is not repeated anywhere else or is unlikely to change) this might be a valid option.
In general, if the constants are specific to the layout of a particular UI component then it seems to make sense to #define them in the header file for the UI component that uses them - I think putting them all in one global file breaks the decoupling that you'd like to have between user interface components, and also for readability it can be easier for another dev to find them in the header file.
On the other hand if there are values that are used consistently across multiple UI components within the one application, then these can be defined in a global include file. Similarly if there are 'base' values that are used to derive other lengths etc. that are used commonly across multiple UI components these also can be stored in a global include.
Also whereever possible make use of the layout manager margin flexibility settings and width/height flexibility settings to minimise the need to hard code values. And when relevant, derive values from a base value or a system value (e.g. screen width).
At the end of the day if the value is there in code in front of you sometimes that much easier to figure out and tweak than changing a #define off in some other file - on the other hand - if the same value is repeated in multiple places and a #define is not used, then it can be very confusing for another coder to come in and change one of these repeated values only and try to understand and sift through the resultant side effects and which other places the value should be changed.
Well Ryan that depends upon you..
You can either use pre processor directives..
declaring in .pch file.
or you can either make an object class taking all the constants....
Hope that will help you..
Thanks
This is what I have learnt from few of my previous projects.
1] Naming conventions - use appropriate and standardized prefix. ex tblRecordLis, viewControlPanel etc.
2] Keep Constants together - keeping all constants at one place reduces the pain of searching entire project to find/fix/replace constants and their values.
3] Grouping relevant Classes together according to utility and their functionality.
4] UI constants like size, offsets , frame values (Which you need to hard code) can be kept in constants
a few which I used are
#define MenuPopoverFrame CGSizeMake(278, 550);
#define LandscapeContentSize #"{{0,0},{719,734}}"
#define PortraitContentSize #"{{2,0},{765,980}}"
5] Using IB as much as possible as it gives us more flexibility.
6] PROPER commenting and documentation proves to be a life saver when dealing with debugging.
I find it easy to declare keys as constants as using them at multiple places also increases the chances of error if used as such. eq key named #"method" can be better declared as
#define kMethodKey #"method"
This very simple thing saves my time while debugging when the project size grows larger.
** Taking hints from Apple's samples also gives you a great help in keeping your code standardized.

Getting maximum performance when making views

I'm developing an app based on a TabBarController.
I have 2 views that do some similar actions.
My question is, should I make 2 different classes or should I use only one class with some "if" statements asking if is a class is one or the other. I need maximum performance on this.
The 2 views load a MKMapView, so I need to know if it is better to load just one object that does the entire thing, or two objects that do similar things.
Thanks!
In Object Orientation it's important to bear in mind the difference between a class and instances of that class.
If you ever find yourself thinking of writing some code in a class that says "What class am I? If I'm class X, do thing A; otherwise do thing B" -- don't! It's a classic problem begging for a nice object oriented solution. There are two common solutions in this kind of situation:
1) Write a single class that at instantiation time gets passed in some vital information that it then uses later. Then another part of your code is making instances of this class configured in the correct way -- e.g. in your problem, two instances of this class get made, each with a different bit of info (map location perhaps?) passed into the init method
2) Write a superclass that has two subclasses that specialise the general bahaviour of the superclass. So most of your logic and code goes in the superclass - suppose it's called MapDisplayViewController - but then you extend this class with two subclasses called (for example) MapDisplayViewControllerA and MapDisplayViewControllerB that override one or more methods in important, different ways to differentiate them.
For your problem it sounds like approach 1) would be good.
Having code which says "What class am I?" is often a good example of a 'code smell' -- in other words, a sign that something could be designed much better.
I would say load two objects. iOS will automatically unload your currently not displayed views if it needs more resources anyway. (Assuming you implemented viewDidLoad and viewDidUnload properly, of course).
In addition, if in case your view needs to initialize/load a lot of data when tab is switched, and the common flow involves the user switching from one tab to another frequently, the app may appear to lag during frequent loading, if you use only 1 object. No one likes long and frequent loading times.
Just my opinion though, based on the information your original post provides. A lot of additional factors can still come into play.

GWT & MVP - Best practices for displaying/editing complex objects?

All the GWT / MVP examples I've learned about seem too simplistic to give a clear view what best practises are regarding displaying and handling slightly more complex model objects.
For example, most examples are something like a presenter that attaches a click handler to a few TextBoxes on the view...if save is clicked, the presenter's save() is called which simply gets the updated values, and we're done, MVP style. That's not so realistic though.
For example, let's say we have:
PresenterX
- gets a 'model' object, let's say any object with an unknown number of various primitives or whatever
ViewX
- should show the model object in a table, and/or allows it to be edited/re-saved
...so that sounds very, very basic. But, we don't know the amount of fields in the model object that we will need to display. So that might relate to a dynamic number of rows/columns. Probably no problem for a table...but how should the presenter give this to the view's table? As the model object that the view understands, or break it down into a bunch of Lists...that the view essentially still has to understand.
Also, certain fields might be editable, of which are unknown until we get the model object (something in the model determines what fields are editable, say) -- so who should be responsible for figuring out what is editable or not? Probably the presenter, but how do we refelct that in the view, the MVP way?
Lastly, let's say there's a 'save' button on the view...who's job is it to figure out all the rows in the table which were changed?
Seems to me that the view either needs to understand the model more, or the presenter needs to really understand the view more -- neither of which are nice MVP :( ... Or perhaps there should be some intermediary object.
I know there are some nicer/newer helpful ways for this kind of stuff (Editors/RequestFactory, etc.), but I'm looking for suggestions on the above scenarious.
As I understand it, MVP is a line with M-P-V points. So P interacts with both, but M and V only with P.
Also, one of design objectives of MVP is to have a testable P and M, which means that V must be replaceable with a mock version. So, V should not expose any implementation-dependent interfaces (e.g. HasClickHandlers instead of Button).
Now, if V should show generic table, you should create generic methods: addColumn(..) to define columns and addRow(..) to add data. The new CellTable is pretty flexible and supports adding columns dynamically.
About changes - V should notify, P should act. Also, there are the new Editors, which IMHO do not fit nicely into MVP, but are supposed to be easy to use.

Design - When to create new functions?

This is a general design question not relating to any language. I'm a bit torn between going for minimum code or optimum organization.
I'll use my current project as an example. I have a bunch of tabs on a form that perform different functions. Lets say Tab 1 reads in a file with a specific layout, tab 2 exports a file to a specific location, etc. The problem I'm running into now is that I need these tabs to do something slightly different based on the contents of a variable. If it contains a 1 I may need to use Layout A and perform some extra concatenation, if it contains a 2 I may need to use Layout B and do no concatenation but add two integer fields, etc. There could be 10+ codes that I will be looking at.
Is it more preferable to create an individual path for each code early on, or attempt to create a single path that branches out only when absolutely required.
Creating an individual path for each code would allow my code to be extremely easy to follow at a glance, which in turn will help me out later on down the road when debugging or making changes. The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same.
Creating a single path that would branch out only when required will be a bit messier and more difficult to follow at a glance, but I would create less code by placing conditionals only at steps that are unique.
I realize that this may be a case-by-case decision, but in general, if you were handed a previously built program to work on, which would you prefer?
Edit: I've drawn some simple images to help express it. Codes 1/2/3 are the variables and the lines under them represent the paths they would take. All of these steps need to be performed in a linear chronological fashion, so there would be a function to essentially just call other functions in the proper order.
Different Paths
Single Path
Creating a single path that would
branch out only when required will be
a bit messier and more difficult to
follow at a glance, but I would create
less code by placing conditionals only
at steps that are unique.
Im not buying this statement. There is a level of finesse when deciding when to write new functions. Functions should be as simple and reusable as possible (but no simpler). The correct answer is almost never 'one big file that does a lot of branching'.
Less LOC (lines of code) should not be the goal. Readability and maintainability should be the goal. When you create functions, the names should be self documenting. If you have a large block of code, it is good to do something like
function doSomethingComplicated() {
stepOne();
stepTwo();
// and so on
}
where the function names are self documenting. Not only will the code be more readable, you will make it easier to unit test each segment of the code in isolation.
For the case where you will have a lot of methods that call the same exact methods, you can use good OO design and design patterns to minimize the number of functions that do the same thing. This is in reference to your statement "The downside to this is that I will increase the amount of code written by calling some of the same functions in multiple places (for example, steps 3, 5, and 9 for every single code may be exactly the same."
The biggest danger in starting with one big block of code is that it will never actually get refactored into smaller units. Just start down the right path to begin with....
EDIT --
for your picture, I would create a base-class with all of the common methods that are used. The base class would be abstract, with an abstract method. Subclasses would implement the abstract method and use the common functions they need. Of course, replace 'abstract' with whatever your language of choice provides.
You should always err on the side of generalization, with the only exception being early prototyping (where throughput of generating working stuff is majorly impacted by designing correct abstractions/generalizations). having said that, you should NEVER leave that mess of non-generalized cloned branches past the early prototype stage, as it leads to messy hard to maintain code (if you are doing almost the same thing 3 different times, and need to change that thing, you're almost sure to forget to change 1 out of 3).
Again it's hard to specifically answer such an open ended question, but I believe you don't have to sacrifice one for the other.
OOP techniques solves this issue by allowing you to encapsulate the reusable portions of your code and generate child classes to handle object specific behaviors.
Personally I think you might (if possible by your API) create inherited forms, create them on fly on master form (with tabs), pass agruments and embed in tab container.
When to inherit form and when to decide to use arguments (code) to show/hide/add/remove functionality is up to you, yet master form should contain only decisions and argument passing and embeddable forms just plain functionality - this way you can separate organisation from implementation.