Creating and using Singleton in flutter dart - flutter

I am very new to flutter and dart and trying to use singleton instance for global state(?).
which is company info that gets from backend server.
When flutter app starts, send request to the server and get a response and build a singleton instance based on the response.
So I created class
class Company {
static final Company _instance = new Company._internal();
factory Company() {
return _instance;
}
#protected
String name;
#protected
String intro;
String get companyName => name;
String get companyIntro => intro;
void setCompany(String name, String intro) {
name = name;
intro = intro;
}
Company._internal();
}
in main.dart
// companyResult is the response from server
final String companyName = companyResult["name"];
final String companyIntro = companyResult["intro"];
// create singleton instance
var company = Company();
// set company info
company.setCompany(companyName, companyIntro);
// cheking
print(company.companyName)
prints null
What am I doing wrong?

Singletons are better avoided, I would recommend that you use Provider instead and inject a simple object reference on your widget tree, so you can grab that reference whenever you want.
The reason your example prints null is because you are wrongly referencing your variables on setCompany(), the variables name and intro are all the same variable, you are changing the variables internal to the function, not the class variables, in order to fix it change it to:
void setCompany(String name, String intro) {
this.name = name;
this.intro = intro;
}
Also, I would suggest you name your variables _name and _intro, as there's no sense in having a get for a variable that's no private.

Related

Flutter Dart | How to return different object from class Constructor

In Dart, is it possible for a constructor to cancel object creation and return a different object instead?
Use case:
Users contains a static map that maps ids to User objects.
When a User is initialized, I want the User constructor to check if User with id is already created, if so: return existing User object, else create a new User object
Example (of-course not working):
class Users {
static const Map<String, User> users = {};
}
class User {
final String id;
final String firstName;
User({required id, required firstName}) {
// If user with id already exists, return that object
if (Users.users.containsKey(id) {
return Users.users[id];
}
// Else, initialize object and save it in Users.users
this.id = id;
this.firstName = firstName;
Users.users[id] = this;
}
}
Question: IS there any way to get the above pseudo code to work?
As mentioned by jamesdlin you should use a factory constructor. Here's what is mentioned in the documentation:
Use the factory keyword when implementing a constructor that doesn’t
always create a new instance of its class.
And in your case this is exactly what you want. Now here's a code sample that does what you want:
Code sample
class Users {
// Also your Map cannot be const if you want to edit it.
static Map<String, User> users = {};
}
class User {
final String id;
final String firstName;
/// Base private constructor required to create the User object.
User._({required this.id, required this.firstName});
/// Factory used to create a new User if the id is available otherwise return the User
/// associated with the id.
factory User({required String id, required String firstName}) {
// If user with id already exists, return that object
if (Users.users.containsKey(id)) {
// Force casting as non nullable as we already checked that the key exists
return Users.users[id]!;
}
// Else, initialize object and save it in Users.users
final newUser = User._(id: id, firstName: firstName);
Users.users[id] = newUser;
return newUser;
}
}
Try the full code on DartPad
You can create a function in class to handle things you want. Here's what you can implement.
class Player {
final String name;
final String color;
Player(this.name, this.color);
Player.fromPlayer(Player another) :
color = another.color,
name = another.name;
}
If this is for caching purposes or you are not creating multiple instances of the Users class, I would suggest using a pattern where static is responsible for a list of class instances. Sometimes this helps to significantly reduce the amount of code:
class User {
static final Map<String, User> users = {};
final String id, firstName;
User._({required this.id, required this.firstName});
factory User({required String id, required String firstName}) => users[id] ??= User._(id: id, firstName: firstName);
}

How to recreate singleton instance if different params are passed to the constructor in dart

I gathered the following understanding for creating a singleton in dart with params
class Foo extends ChangeNotifier {
late String channel;
void instanceMemberFunction () {
print('Foo created with channel $channel')
}
static final Foo _instance = Foo._internal();
Foo._internal() {
instanceMemberFunction();
}
factory Foo({
required String channel
}) {
_instance.channel = channel;
return _instance;
}
}
and I am calling the instance like so
Foo({channel: "bar"})
Now I want to have some working that if I use
Foo({channel: "baz"})
Then a new instance is created and it's okay in that case to destroy the old one. How can I achieve this in dart?
It seems like you've copied some existing example for creating a singleton without fully understanding what it's doing and why. The core parts are:
The single instance is stored in a global or static variable.
The class has one or more public factory constructors that returns that global/static variable, initializing it if necessary.
All other constructors for the class are private to force consumers to go through the factory constructors.
Therefore, if you want your factory constructor to replace its singleton based on its argument, you need to:
Make your factory constructor check if the argument is appropriate for the existing instance. If it is, return the existing instance. If not (or if there is no existing instance), create and return a new instance.
Since you need to check if the existing instance is initialized, make it nullable. (You alternatively could initialize it to a non-null sentinel value, e.g. Foo._internal(channel: '').
Pass the argument along to the private constructor.
class Foo extends ChangeNotifier {
final String channel;
void instanceMemberFunction () {
print('Foo created with channel $channel');
}
static Foo? _instance;
Foo._internal({required this.channel}) {
instanceMemberFunction();
}
factory Foo({required String channel}) {
if (channel != _instance?.channel) {
_instance = Foo._internal(channel: channel);
}
return _instance!;
}
}
Note that this implementation will create a new object if the constructor argument changes, which isn't very singleton-like. Depending on what you want to do, you could:
Return a new object (which could allow multiple simultaneous instances).
Return the existing object.
Return the existing object, but mutate it with the constructor argument.

Unable to make a Dart class object

My Code
class Book {
String title;
String author;
int numOfPages;
Book(String title, String author, int pages) {
this.title = title;
this.author = author;
this.numOfPages = pages;
}
}
void main() {
Book bk = Book("Modern Operating Systems", "S.Tannabeaum", 1250);
print(bk.title);
}
Hey, I'm pretty a newbie to dart and programming. Here actually I wanted to make a class and it's constructor and three instances within it. And when I wanted to make an object from this class, I caught up with this error!
My code's error message!
I think something is wrong with my code, any help would be appreciable:)
There are two problems in your code. First, constructors in Dart has two "phases" where you first initialize the object and then runs the constructor body before returning the object to the caller of the constructor.
That means that you are here creating a Book object first without setting the three variables. Yes, you are setting these variables later in the constructor body but at that time it is too late.
The next problem is that if you are not setting value for a variable in Dart it will always default to the value null. With Dart 2.12, we got non-nullable types by default (NNBD) which mean all types in Dart does not allow the value null unless specified. You specify the validity of the null value by typing a ? after the name of the type. E.g. String? allows a variable to point to a String object, or null.
In this case, we don't need to specify nullable types since the problem is mostly you need to move the initialization of the variables from the constructor body in to initialization phase of the object like this:
class Book {
String title;
String author;
int numOfPages;
Book(String title, String author, int pages)
: this.title = title,
this.author = author,
this.numOfPages = pages;
}
The same can be rewritten as the following which is also the recommended way to do it:
class Book {
String title;
String author;
int numOfPages;
Book(this.title, this.author, this.numOfPages);
}
Since we are here just directly referring to each field we want to give a value. Dart will then automatically assign the values with the parameters from the constructor.
If your constructor takes a lot of arguments, it might be more readable to use named arguments. The required keyword here means that we most provide a given named parameter. If not specified, the named argument is optional (which means we most provide a default value or allow null for our parameter to be valid):
class Book {
String title;
String author;
int numOfPages;
Book({
required this.title,
required this.author,
required this.numOfPages,
});
}
void main() {
final book = Book(
title: "Modern Operating Systems",
author: "S.Tannabeaum",
numOfPages: 1250,
);
print(book.title); // Modern Operating Systems
}

Dart Flutter How to initialize a class method inside of its class?

Here is my class:
class WorldTimeClass {
String flag;
String url;
String time;
String location;
WorldTimeClass({this.flag, this.url, this.time, this.location});
Future<String> getData() async {
try{
Response load = await get('http://worldtimeapi.org/api/timezone/$url');
Map x(){if(load.statusCode == 200){
print(load.statusCode);
Map map = jsonDecode(load.body);
return map;}
else{
print('No Access');
return {1:'NoAccess.'};}
}
Map myMap = x();
String datetime = myMap['utc_datetime'];
String offsetUTC = myMap['utc_offset'];
DateTime dateTimeObjectConvert = DateTime.parse(datetime);
// Below converts the datetime string to a DateTime Object and then converts the UTC Offset to a substring only '01' out of +01:00 and then converts it to an int Object and then adds it to the DateTime Object as a Duration (hours);
dateTimeObjectConvert = dateTimeObjectConvert.add(Duration(hours: int.parse(offsetUTC.substring(1,3))));
return time = dateTimeObjectConvert.toString();
}
catch(e,s){
return 'Could not access time data from API.\nWe are sorry, please try again.\nError occured: $e';
}
}
var myString = getData().then((value) => value);
DateFormat pretty = DateFormat().add_jm().format(myString);
}
How can I access myString and execute it inside my class in order to use the resulting String object to use it inside a second method pretty ?
Also, I need to understand what does the below exception mean?
Only static members can be accessed in initializers.
Only static members can be accessed in initializers.
This basically means that you cannot call methods of a class or access properties of a specific class directly under class declaration.
You are getting the error on those two lines:
var myString = getData().then((value) => value);
DateFormat pretty = DateFormat().add_jm().format(myString);
Therefore create a method that returns a String then all you have to do is to call that method and it will give you the String, and add the code above inside the method:
String getDateFormat(){
var myString = getData().then((value) => value);
return DateFormat().add_jm().format(myString);
}
To access your myString variable you'll have to do one of those things:
Instantiate an WorldTimeClass object and access it using yourWorldClassObject.myString
Make it into in static member by using the static keyword like static var myString. This is what " Only static members can be accessed in initializers. " is all about. You have to create an instance of the class if you want to access it's properties, or make them static to access them without the need to instantiate an object. Simply WorldTimeClass.myString.

Dart Named constructor vs Static method what to prefer?

So after dart made new keyword optional,
we can initialize an object with exact same syntax but different internal implementation.
class Color {
int r = 0, g = 0, b = 0;
Color({this.r, this.b, this.g});
//Named constructors
Color.red() //Implementation
Color.cyan() //Implementation
// Static Initializers
static Color red() => //Initialze with parameter
static Color cyan() => //Initialze with parameter
}
We can use them like this regardless of being it a named constructor or static method:
Color red = Color.red();
Color cyan = Color.cyan();
What is the place to use each of them?
In practice there is little difference between a factory constructor and a static method.
For a generic class, it changes where you can (and must) write a type parameter:
class Box<T> {
T value;
Box._(this.value);
factory Box.withValue(this.value) => Box<T>._(value);
static Box<T> fromValue<T>(T value) => Box<T>._(value);
}
...
var box1 = Box<int>.withValue(1);
var box2 = Box.fromValue<int>(2);
So, for generic classes, factory constructors are often what you want. They have the most pleasant syntax.
For non-generic classes, there is very little difference, so it's mainly about signaling intent. And deciding which category the name goes into in the DartDoc.
If the main objective of the function is to create a new object, make it a constructor.
If the main objective is to do some computation and eventually return an object (even if it's a new object), make it a static function.
That's why parse methods are generally static functions.
In short, do what feels right for your API.
Constructors and static functions are different. You usually create a named constructor that returns an instance of an object with some predefined values. For example, you have a class called Person which stores Name and Job. You can create this named constructor Person.doctor(name) which you will return a Person object with Job = 'doctor'
class Person{
final name;
final job;
Person(this.name, this.job);
Person.doctor(this.name, {this.job = "doctor"});
}
Static functions or variable persists on all the instance of a class. Let us say, Person has a static variable called count. You increment the count variable whenever an instance of Person is created. You can call Person.count anywhere later in your code to get the value of count (Number of instances of Person)
class Person{
final name;
final job;
static int count;
Person(this.name, this.job){
count++;
}
Person.doctor(this.name, {this.job = "doctor"});
}
Another very useful feature of static class methods is that you can make them asynchronous, i.e. wait for full initialisation in case this depends on some asynchronous operation:
Future<double> getCurrentPrice(String ticker) async {
double price;
// for example, fetch current price from API
price = 582.18;
return price;
}
class Stock {
String ticker;
double currentPrice=0.0;
Stock._(this.ticker);
static Future<Stock> stockWithCurrentPrice(String ticker) async {
Stock stock = Stock._(ticker);
stock.currentPrice = await getCurrentPrice (ticker);
return stock;
}
}
void main() async {
Stock stock = await Stock.stockWithCurrentPrice('AAPL');
print ('${stock.ticker}: ${stock.currentPrice}');
}
Another benefit of the distinction between named constructor and static function is that in the documentation generated the function will be either filed in the construction section or the methods section, which further makes it's intentions clearer to the reader.
A person looking for a constructor in the constructor section of the documentation will easily discover the named constructors as opposed to having to also dig through the static functions section too.