Basics of Dart: Access class paramters - flutter

I have started learning Dart and Flutter and wanted to understand one concept:
Updated code: try in dartpad
class Service{
String ask = '';
void write (String receivedData){
ask = receivedData;
}
}
class WriteNow{
String hi = 'hi';
Service art = Service();
void okay () {
art.write(hi);
}
}
void main () {
WriteNow a = WriteNow();
a.okay();
Service b = Service();
print(b.ask);
}
I run WriteToService first and then ReadFromService, I cannot get the 'Hello', but get the original string ''. Please clarify. Also, how does this scale?

You are creating different instances of the Service class, that's the reason you can't get the updated String. Let me explain, in this piece of code:
WriteNow a = WriteNow();
a.okay();
You are creating an instance of the Service class, called art. The art instance has its member called ask, which is empty. When you call a.okay(), you are modifying the ask member of the art instance. So now, if you run this print(a.art.ask) you will get the 'hi' response.
Instead of that, you are creating another instance of the Service class, called b, and then you are printing the b.ask value. Can you see the error? You modified the art instance, not the b instance.
The ask value is not "global" to all the instances of the Service class, each instance has its own ask value, and each instance can change it without modifying the other instances.

class Service {
String ask = '';
void write (String receivedData){
ask = receivedData;
}
}
class WriteToService{
Service a = Service();
a.write('hello');
}
class ReadFromService {
Service b = Service();
print(b.ask);
}
What you are Doing:
Step 1: The Service class contains String ask = '';
Step 2: Running WriteToService class
Step 3: Running ReadFromService class
So ReadFromService class displays original String content which is ask = '' as it has been reassigned to String ask = ''. Scope of the previous entry hi of WriteToService class was ended.
Correct way to do it:
void main() {
WriteToService ok1 = new WriteToService();
ReadFromService ok2 = new ReadFromService();
}
String globelVariable = 'hi';
class Service {
String ask = globelVariable;
void write(String receivedData) {
globelVariable = receivedData;
}
}
class WriteToService {
Service a = new Service();
WriteToService() {
String name = "hello";
a.write(name);
}
}
class ReadFromService {
Service b = new Service();
ReadFromService() {
print(b.ask1);
}
}
Now declare a global variable String globelVariable = 'hi'; and assign it to String ask = globelVariable; in class Service. In write method assign the receiving data to global variable globelVariable = receivedData;. Since the scope of global variable doesn't end till the program is terminated it won't loose the value of the string hello which is eventually printed when ReadFromService class is called.
Test the above code at https://dartpad.dev/

Related

Flutter Getx: Can obs create a global variable?

How to make obs a global variable?
Have an option of Getx that can create a global variable?
For the example:
class Test extends GetxController {
RxString a = "".obs;
}
Page 1:
Test test = Get.put(Test());
print(test.a.value); //""
test.a.value = "55555";
print(test.a.value); //"55555"
Page 2:
Test test = Get.put(Test());
print(test.a.value); //""
You can insert your class into main with Get.put(Test()); and it would be something like:
void main() {
Get.put(Test());
runApp(...);
}
In your test class add the following code: static Test get to => Get.find<Test>();
Your Test class would look like this:
class Test extends GetxController {
static Test get to => Get.find<Test>();
RxString a = "".obs;
}
Now you have your global class and to send it to call it would be as follows:
Test.to.a
You would use it in the following way:
//IMPORT TEST CLASS
//get the same instance that has already been created
Test test = Test.to.a;
print(test.value);
Update
Now, I am using
Class + static
Class:
Class Global {
static Rx<String> name = "me".obs;
static ProfileObject profile = ProfileObject();
}
Use:
Obx(()=>Text(Global.name.value)),
Obx(()=>Text(Global.profile.age.value)),
It is easy to use, don't setting just use static in class.
Get.put() creates single instances, however, if you want to create a global controller, there's Get.find() which fetches the last instance of the controller created and shares it, that way global access can be achieved.
You can read more about this here
Note, to use Get.find(), an instance needs to be created earlier.
Your new code will look like this:
class Test extends GetxController {
RxString a = "".obs;
}
Page 1:
Test test = Get.put(Test());
print(test.a.value); //""
test.a("55555");
print(test.a.value); //"55555"
Page 2:
Test test = Get.find<Test>();
print(test.a.value); //"55555"
If your work needs the latest value you can follow the comment of #Sagnik Biswas. It works!
Now, I am using basic globals instances.
test_cont.dart:
TestCont testContGlobals = Get.put(TestCont());
class TestCont extends GetxController {
RxString a = "".obs;
}
But I still think my method might not be correct.
Are there any disadvantages to this method?

Difference between assign values for the variables of a class [duplicate]

This question already has answers here:
Should I initialize variable within constructor or outside constructor [duplicate]
(11 answers)
Closed 6 years ago.
What is the difference between below 2 ways of assigning values for variables of a class.
Class A{
Private Variable v = someValue;
}
vs
Class A{
private Variable v;
//constructor
public A(){
this.v = someValue;
}
}
Can someone please explain?
There is no real difference from a code execution point of view.
As a previous answer says, I prefer declaring the variable outside of the constructor; for example:
public class A {
private int aValue = 100;
}
Instead of
public class A {
private int aValue;
public A() {
this.aValue = 100;
}
}
The reason being that if you have multiple constructors, you do not have to keep writing this.aValue = 100; and you are unable to "forget" to initialize the variable in a constructor.
As others have said however, there are times when it is better to initialize the variable in the constructor.
If it will change based on values passed to it via the constructor, obviously initialize it there.
If the variable you are initializing may throw an error and you need to use try / catch - it is clearly better to initialize it in the constructor
If you are working on a team that uses a specific coding standard and they require you to initialize your variables in the constructor, you should do so.
Given freedom and none of the above, I still declare it at the top - makes it much easier to find all of your variables in one place (in my experience).
See this duplicate answer: https://stackoverflow.com/a/3919225/1274820
What is the difference between below 2 ways of assigning values for
variables of a class.
Generally nothing, but ...
class constructor is an entry point when creating a new instance, so all assignments should be done there for readability and maintainability.
When you want create a new instance you start reading a source code at the constructor. Here is an example. All informations about new instance are in one proper place.
public class C {
private int aValue;
private int bValue;
private int cValue;
private int dValue;
public C(int a, int b) {
this.aValue = a;
this.bValue = b;
this.cValue = a * b;
this.dValue = 1000;
}
}
If you look at the MSIL of this class:
namespace Demo
{
public class MyClass
{
private string str = "hello world";
private int b;
public MyClass(int b)
{
this.b = b;
}
}
}
.method public hidebysig specialname rtspecialname
instance void .ctor(int32 b) cil managed
{
// Code size 25 (0x19)
.maxstack 8
IL_0000: ldarg.0
IL_0001: ldstr "hello world"
IL_0006: stfld string Demo.MyClass::str <---- RIGHT HERE
IL_000b: ldarg.0
IL_000c: call instance void [mscorlib]System.Object::.ctor()
IL_0011: ldarg.0
IL_0012: ldarg.1
IL_0013: stfld int32 Demo.MyClass::b
IL_0018: ret
} // end of method MyClass::.ctor
You can see that the constructor is "injected" with the assignment of this.str = "hello world".
So once your code is compiled, there is no difference what so ever. Yet, there are quite a few good reasons why you should not do it (user1274820's answer has some them)

Accessing beans in View Class

Hi I'm still very new to SugarCRM and trying to get my head round sugars MVC.
I'm making a module which doesn't have its own SugarBean instead it needs to interact with the Contacts Beans and Quotes Bean.
My example code is below.
My Question is how can i get access to the $contact_bean and $quote_bean from the controller.php in the view.searchengineer.php file so i can call information from them after the records have been loaded.
controller.php
Class PCP_TasksController extends SugarController
{
function action_search_engineers()
{
// Get Contacts ID
$contact_id = $_GET['Contact_id'];
//Load Contacts Bean and pull Record
$contact_bean = New Contact();
$contact_bean->retrieve($contact_id );
//Get Quote ID
$quote_id = $_GET['Quote_id'];
//Load Quotes Module and pull record
$quote_bean = New AOS_Quotes();
$quote_bean->retrieve($quote_id );
$this->view = 'SearchEngineer';
}
}
views/view.searchengineer.php
class PCP_tasksViewSearchengineer extends SugarView
{
function display() {
Echo "The Contact Name is ";
Echo "The Quote Ref is ";
}
}
I'd just put that same code directly in the view instead.

NUnit with Rhino Mocks exception: Why is it throwing this exception?

I'm getting an exception that really makes no sense to me whatsoever.
I have an Expect call for a method that takes 3 arguments into it: The types are called CallContext, IDal, and List.
NUnit throws me 2 exceptions: One for not expecting a method call that happened where the types are CallContext, System.Object, and List, and one for expecting a call that didn't happen where the types are the correct ones. The fun thing is that the only way to call the method is with the 3 types mentioned above. There is no method call with type object!
Here is the code:
private IDal mockDal;
private CallContext mockContext;
private IWorkbooksLogic mockWLogic;
private ICommercialSpaceLogic mockCLogic;
private CmWorkbook mockWorkbook;
private IList<Workbook> mockList;
private MockRepository mock;
private Random random;
[SetUp]
public void Setup() {
mock = new MockRepository();
random = new Random();
this.mockDal = mock.StrictMock<IDal>() as IDal;
this.mockContext = new CallContext();
this.mockWLogic = mock.StrictMock<IWorkbooksLogic>() as IWorkbooksLogic;
this.mockCLogic = mock.StrictMock<ICommercialSpaceLogic>() as ICommercialSpaceLogic;
this.mockWorkbook = new CmWorkbook();
this.mockList = mock.StrictMock<IList<Workbook>>() as IList<Workbook>;
}
[Test]
public void ShouldFailWhenCreateWorkbookFails() {
int randBudget = random.Next(50);
int randEntity = random.Next(50);
int randWork = random.Next(50);
WorkbookDefinitions work = new WorkbookDefinitions {
WorkbookDefinitionID = randWork
};
Budget budget = new Budget {
BudgetID = randBudget,
WorkbookDefinitions = new List<WorkbookDefinitions> { work },
};
CommercialProperty property = new CommercialProperty {
CommercialPropertyID = randEntity,
CMEntity = new CMEntity {
EntityBase = new EntityEntity { EntityCode = "random.Next(50)" }
}
};
CmWorkbook book = new CmWorkbook {
WorkbookName = String.Format("CM — {0}", property.CMEntity.EntityBase.EntityCode)
};
OperationResults results = new OperationResults();
this.mockList.Add(book);
using (mock.Record()) {
Expect.On(this.mockDal).Call(this.mockDal.GetObject<Budget, int>(randBudget)).Return(budget);
Expect.On(this.mockDal).Call(this.mockDal.GetObject<CommercialProperty, int>(randEntity)).Return(property);
Expect.On(this.mockWLogic).Call(this.mockWLogic.Create(this.mockContext, this.mockDal, this.mockList)).Return(null);
}
using (mock.Playback()) {
results = CmWorkbookLogic.CreateWorkbook(mockContext, mockDal, mockWLogic, mockCLogic, randBudget, randEntity);
}
Assert.IsFalse(results.AllSuccessful);
}
The method being called is: workbooksLogic.Create(context, dal, new List { workbook })
Here is the NUnit error:
ShouldFailWhenCreateWorkbookFails:
Rhino.Mocks.Exceptions.ExpectationViolationException : ICRUDBaseLogic`1.Create(CallContext, System.Object, System.Collections.Generic.List`1[Workbook]); Expected #0, Actual #1.
ICRUDBaseLogic`1.Create(CallContext, IDalProxy8768e63f86da4601993b4791c696ada6, System.Collections.Generic.List`1[Workbook]); Expected #1, Actual #0.
I have no idea what the heck is going on with this. Anyone have any ideas?
Rhino Mocks uses the overloaded Equals method to compare arguments of the expected invocation and the invocation that actually happened. Some of the objects you are supplying as arguments don't have Equals overloaded (i.e. List class, not sure about the others), so the only way it would work if the supplied arguments had the same references (so were the same objects) as the ones you used to set up the expectation.
You have a few options:
Use IgnoreArguments, so that arguments will not be checked at all
Provide your own constraints, so that you can check if the arguments are what you expect them to be, but without using Equals()
Make sure these are exactly the same objects (if possible)

EFPocoAdapter -- PopulatePocoEntity has null PocoEntity

I'm trying EF with the EFPocoAdapter for the first time. I have a relatively simple TPH scenario with one table and two types, each inheriting from an abstract base class.
My model validates through EdmGen, and my PocoAdapter.cs and xxxEntities.cs files generate fine as well. (well, actually, there are some namespace problems that I'm currently tweaking by hand until we figure out where to go next.)
When I run a simple test to retrieve data:
using (CINFulfillmentEntities context = new CINFulfillmentEntities())
{
// use context
var alerts = from p in context.Notifications.OfType<Alert>()
select p;
foreach (var alert in alerts)
{
Assert.IsNotNull(alert);
}
}
I get an error in the PocoAdapter class, claiming that PocoEntity is null is the following method inside my base class's adapter:
public override void PopulatePocoEntity(bool enableProxies)
{
base.PopulatePocoEntity(enableProxies);
PocoEntity.Owner = _Owner.CreatePocoStructure();
if (!(PocoEntity is IEntityProxy))
{
}
}
Any ideas from anyone?
So, after a little more debugging, I think this is related to proxies. Inside PocoAdapterBase we have the following method:
protected PocoAdapterBase(TPocoClass pocoObject)
{
_context = ThreadLocalContext.Current;
bool allowProxies = false;
if (_context != null)
{
allowProxies = _context.EnableChangeTrackingUsingProxies;
}
_pocoEntity = pocoObject ?? (TPocoClass)(allowProxies ? CreatePocoEntityProxy() : CreatePocoEntity());
Init();
InitCollections(allowProxies);
RegisterAdapterInContext();
}
The line that sets _pocoEntity calls CreatePocoEntityProxy, which returns null.
More info as I find it.