As far I been to doc's and tutorials I got to know we need to use underscore to define properties or methods but from by below code I can still access it.
void main() {
User d = new User('John Doe', 5);
print(d._name);
}
class User {
String _name;
int age;
User(this._name, this.age);
String respectedName(nname) {
return 'Mr.$nname';
}
}
I am not sure that I understand how things works in Dart, please help.
There is smiler question answered here, but that's still not much of a helpful answer to me.
Private properties/methods in dart are accessible for the whole file and not accessible from other files.
This can be combined with part/part of keyword to treat two+ files as one.
Related
Let say I have class like this
class OrderInfo {
final String orderId;
final String status;
final DateTime orderDateTime;
final DateTime? deliverDateTime;
final String? restaurantTitle;
OrderInfo({
required this.orderId,
required this.status,
required this.orderDateTime,
required this.deliverDateTime,
required this.restaurantTitle,
});
// and a getter
Something get something {
// Very long code that I don't want to recalculate
return something;
};
}
Since all fields is final, so there's no point to recalculate (return value will be the same).
I tried create field like this.
late Something something = () {
// Very long code that I don't want to recalculate
return something;
}();
But I'm not sure this is correct way to do.
Is there other method or this is fine?
The late field is fine. I'd make it final, unless you want to allow overwriting the value.
I'd probably extract the computation function into a named helper function, like:
class OrderInfo {
late final Something something = _computeSomething();
...
Something _computeSomething() {
// Very long code that I don't want to recalculate
return something;
}
}
Keeping the computation on the side makes the variable declaration more readable, and it allows you to reuse _computeSomething if you want to, but otherwise the effect is the same.
If the Something cannot be null, you can also implement your own late variable:
class OrderInfo {
Something? _something;
...
Something get something => _something ??= _computeSomething();
...
}
The only advantage over a late final .. = ... is that it allows you to check whether the _something has been computed or not.
In some cases that's useful. Say the computation allocates a resource, and you want to release that resource later. If you just use a late variable to store the allocated value, all you can do is read that variable or not. Reading it will allocate the resource, if it wasn't already, and then you have to release it.
Using a nullable variable, you can check whether there is something to release, and do nothing if not.
In general, if you ever need to know whether a late variable has been initialized, consider not using late to begin with, because late hides the "is initialized" bit from you.
Hiding details is what makes the late final something = ...; so nice and short, so using late final is fine when you don't need to know.
(I'd generally recommend against exposing late public fields that are not final, or that do not have an initializing expression, because that will also expose a setter for the field. It either exposes the potentially uninitialize field to your users, risking it throwing when read, or it exposes a setter in your API that users cannot call anyway. A late final variable with an initializer expression is great, because it doesn't have a setter, and it is always initialized when it's read.)
save result into a final variable, then the getter only take the result, it will not recalculate :
class OrderInfo {
final String orderId;
final String status;
final DateTime orderDateTime;
final DateTime? deliverDateTime;
final String? restaurantTitle;
late final Something _somethingFinal;
OrderInfo({
required this.orderId,
required this.status,
required this.orderDateTime,
required this.deliverDateTime,
required this.restaurantTitle,
}){
_somethingFinal = _calculateSomthing();
}
// and a getter
Something get something {
// Very long code that I don't want to recalculate
return _somethingFinal;
}
Something _calculateSomthing(){
return Something();
}
}
class Something{
}
I want to access to a property by the name si string format.
If I have a class like that:
class PrefsState {
String a;
PrefsState({
this.a,
})
How can I do something like that:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test[key]);
Of course is not working. There is a way to do that in Dart ?
Unfortunately, you cannot use reflection/mirrors in flutter.
What you can do, which is tedious, is use maps.
class PrefsState {
String a;
const PrefsState({ this.a, });
dynamic getProp(String key) => <String, dynamic>{
'a' : a,
}[key];
}
It's probably better to build the map in the constructor, but if you want const constructors then you'll have to settle for this. Likely won't make much of a difference unless you have a million parameters anyway. Then you use it like so:
PrefsState test= PrefsState(a: "it is a test");
String key = "a";
print(test.getProp(key));
I don't think there is a less cumbersome way of doing this, but would love to be proven wrong :-)
You can do it with mirrors, but mirrors don't work in dart2js or flutter. You can use code builders to get at this, but the real question is what is your need for this?
Is there a simple way to specify a list of possible values for the parameter orderBy? Not one by one please, otherwise I would not be making the question. I want to specify that orderby makes sense only if it is chosen from a predetermined list. Suppose the list is very large...still not random. This cannot be that hard...no single example of such a simple task.
[Test, AutoData]
public override void IndexReturnsView(int? pageIndex, int? pageSize, string orderBy, bool? desc)
{
.....
}
EDIT:
All I want is to read the possible values from a list as I would do with the ValueSource attribute. However, it seems not to work with AutoFixture. If I specified e.g. [ValueSource("GetOrderByColumnNames")] my test does not work anymore. I have no idea of what I am doing wrong. Unfortunately AutoFixture lacks useful documentation and the examples are very basic. Is there a working example of this scenario that I can use to guide myself here?
This has to be a very common situation, however I have been looking for days with no luck :(.
Appreciated!
If I understand the question correctly, the problem is that the orderBy value should be randomly selected from a list of predefined values, but that list might be too large to use with [InlineAutoData].
The easiest way to do this that I can think of is to introduce a helper type. This might actually be a valuable addition to the application code itself, as it makes the role of various values more explicit, but if not, you can always add the wrapper type to the test code base.
Something like this is the minimum you'll need:
public class OrderCriterion
{
public OrderCriterion(string value)
{
Value = value;
}
public string Value { get; }
}
If we also imagine that this class exposes a list of ValidValues, you can implement an AutoFixture Customization using the ElementsBuilder class:
public class OrderCriterionCustomization : ICustomization
{
public void Customize(IFixture fixture)
{
fixture.Customizations.Add(
new ElementsBuilder<OrderCriterion>(OrderCriterion.ValidValues));
}
}
Then you create a data source attribute for your test code base:
public class TestConventionsAttribute : AutoDataAttribute
{
public TestConventionsAttribute() : base(
() => new Fixture().Customize(new OrderCriterionCustomization()))
{
}
}
This enables you to write a test like this, which passes:
[Theory, TestConventions]
public void IndexReturnsView(
int? pageIndex,
int? pageSize,
OrderCriterion orderBy,
bool? desc)
{
Assert.Contains(orderBy.Value, OrderCriterion.ValidValues.Select(x => x.Value));
}
Notice that instead of declaring the orderBy parameter as a string, you declare it as an OrderCriterion, which means that AutoFixture will be detect its presence, and the Customization then kicks in.
See also https://stackoverflow.com/a/48903199/126014
I'm starting to user Gate in Laravel 5.1, and I got this code from some where in the internet.
<?php
public function boot(GateContract $gate)
{
$this->registerPolicies($gate);
/**
* NOTE!!
* First time migration will fails, because permissions table doesn't exists.
*/
foreach($this->getPermissions() as $permission) {
$gate->define($permission->path, function($user) use ($permission) {
return $user->hasRole($permission->roles);
});
}
}
My question is, what is function($user) use ($permission) { in $gate->define($permission->path, function($user) use ($permission) { ??? Why is there use after function()?
If there're some references, I'd love to know/ read it.
It has been described in document of PHP.
Please refer to the example 3 of http://php.net/manual/en/functions.anonymous.php.
Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct.
Your case is
$user->hasRole($permission->roles)
is necessary in order to use the variable of $permission.
I'm refactoring a Blackberry application and I have a scenario where I think I'm currently using a global variable, but I'm not sure if that's the right thing to do. Briefly, my scenario is the following -
My app first requires the user to login. The (uid, pass) are sent to a web service which determines if the login is valid and returns some additional data. I have a model object on my application that looks something like this - (After a succesfully calling login)
class UserDataModel
{
private String username;
private String password;
private String fullName;
private String age;
...
/* Getters and Setters */
}
I also have a UserPreferencesModel which contains all the preferences that the user has saved. (I need to back them up to our database / restore them across devices etc.)
Additionally, in what context are Globals generally used in the context of mobile development?
Thanks,
Teja.
Well, I made a simple example how you can to use the RuntimeStore, I hope that this be of helpful
public class myData
{
long ID = 0xf46f5a7867d69ff0L;
String d1;
RuntimeStore runTS = RuntimeStore.getRuntimeStore();
public void setData(String _d1)
{
try
{
syncronized (runTS)
{
runTS.put(ID, _d1);
}
}catch(Exception ex){}
}
public String getData()
{
String s;
try
{
s = (String)(RuntimeStore.getRuntimeStore().get(ID));
}catch(Exception ex){}
return s;
}
}
There is nothing particularly special about BlackBerry in regards to using singletons. Of course, true constants should be just statics. And all of them should be final but Strings: there is a memory usage penalty if a static final String is reused often in your code.
What singleton gives you is the ability to replace or remove complex models with relatively long lifetime via a single point of control.
In your example, DataModel is a good candidate. BlackBerry is a personal device, so there is a big chance this DataModel with user profile and, probably, additional data, will survive for the lifetime of the active application.
So,
class UserDataModel
{
private static UserDataModel singleton;
public static void login() {
//get credentials
//authenticate
singleton = new UserDataModel(... user profile data...);
}
public static UserDataModel getInstance() { return singleton; }
private String username;
private String password;
private String fullName;
private String age;
...
/* Getters and Setters */
}
This way of doing it is a valid, a little simplified, example. If something changes (say, server host), all you need to do is to replace singleton. Also, it opens up a possibility to use polymorphism, if UserDataModel implementation is different for different servers, etc. There are many benefits to it at the cost of one extra variable in a chain of accessors. Again, there is nothing special about BlackBerry here, this reasoning is valid in any Java application.
Why the example is simplified is because you need to think about threads. If there is even a remote chance that something somewhere will access getInstance() on a different thread than login(), you have to properly synchronize them (even though I was never able to break a simple object reference by accessing/updating it from different threads on BlackBerry).
their are some scenarios when having static variable is good idea. like for Constant String fields.
here is the link to blackberry official Best practice document for writing efficient code for blackberry platform.
Black Berry: Best Practices: writing efficient code