I am trying to make a plugin for authentication. It will act like a "wrapper" (but with additional functionality for each plugin) for different already existing packages for different platforms.
By the additional functionality I mean
Web implementation already has state management
Android implementation is AppAuth, so here I need to add my own state management
I am trying to use the PlatformInterface way, but I cannot find any guide how to make it instantiable with constructor params.
Let's say I have this code:
abstract class KeycloakAuth extends PlatformInterface {
KeycloakAuth()
: super(token: _token);
static final Object _token = Object();
static late KeycloakAuth _instance = KeycloakAuth._setPlatform();
static KeycloakAuth get instance => _instance;
static set platform(KeycloakAuth instance) {
PlatformInterface.verifyToken(instance, _token);
_instance = instance;
}
factory KeycloakAuth._setPlatform() {
if (Platform.isAndroid) {
return KeycloakAuthAppAuth();
} else {
throw UnimplementedError('The current platform ${Platform.operatingSystem} is not supported.');
}
}
}
This would work, but in my app I would like to do this:
final _keycloakAuth = KeycloakAuth(keycloakUrl: 'xxx', clientId: 'yyy');
If I simply tried to add params like this:
abstract class KeycloakAuth extends PlatformInterface {
final String keycloakUrl;
final String clientId;
KeycloakAuth({
required this.keycloakUrl,
required this.clientId,
})
: super(token: _token);
...
I wouldn't be able to pass them inside the _setPlatform() method since this is static method.
Also KeycloakAuthAppAuth extends KeycloakAuth, so I would need to pass those parameters back and forth, like instantiate KeycloakAuth, this instantiates KeycloakAuthAppAuth which needs to pass those parameters back via super()...
Any tips for this?
I know I can make a method initialize({String keycloakUrl, String clientId}) with my parameters, but I would still like to know if it's possible to make it using the constructor.
Related
I'm building a Flutter application and wanted to define a common scheme for all my pages. All pages should have a static id variable that I use for routing with named routes. (instead of having to instanciate MainMenuPage().id for Navigator.pushNamed(..., MainMenuPage ().id), I prefer to use the MainMenu.id.
In the MainMenuPage page file, this currently looks like:
class MainMenuPage extends StatelessWidget {
const MainMenu();
static String id = 'main-menu-id'; // added by me, but not "enforced" through dart logic
}
I am aware that the flutter-way of Widget-Stacking is composition over inheritance. Still, I was wondering why I cannot create a superclass of all my pages to force them to implement this static variable.
In my imagination this would be looking like this:
abstract class MyAppPage() {
static String id;
}
class NotAbstractPage() extends StatelessWidget implements MyAppPage {
static String id = 'foobar'; // this line is enforced through the quasi-interface
}
Unfortunately, this approach currently does not work in Dart. How could one make this work with some interfacy-ish mechaning?
You can force your pages to implement the variable in your superclass but it shouldn't be a static variable like this :
abstract class MyAppPage {
late String id ;
}
if you Implement this class without overriding this variable it will give you an error :
after overriding it:
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.
I've been struggling with this for a long time.
For sure, what I currently know is that you should use a factory or static fromJson when you need only one object and a Constructor named .fromJson when you need to create multiple instances.
So.. when?? when we need a one instance and when we need multiple instances??
I'm creating a model class for API response right now, and I'm deeply troubled about whether to use the factory or not.
Factory constructor allows returning already created instances. It allows us easily make singletons and multitones. From the call side, it looks like the usual constructor, but from inside implementation, it varies. Also, the factory constructor doesn't force you to return only one instance (object) as you stated. You can create as many as you need. It allows returning already created instances. That's the difference with an ordinary constructor that always returns a new instance. So this feature gives us some flexibility and in some cases performance improvements.
An example:
class Logger {
static Logger _instance;
Logger._() {
print('Logger created');
}
factory Logger() {
return _instance ??= Logger._();
}
void log(String msg) => print('${DateTime.now()}: $msg');
}
void main() {
A().initialize();
B().initialize();
}
class A {
Logger _logger;
void initialize() {
_logger = Logger();
_logger.log('A initialized');
}
}
class B {
Logger _logger;
void initialize() {
_logger = Logger();
_logger.log('B initialized');
}
}
If we run this code it will produce output like that:
Logger created
2021-09-27 21:59:23.887: A initialized
2021-09-27 21:59:23.887: B initialized
Where you can see that only one instance of Logger class has been created. Despite from calling side we've requested to create two instances.
In most cases, if your task it to create a modal class for API response an ordinary constructor with a static fromJson method is enough.
Creating a function that returns an instance of the class is right, but creating a factory that returns an instance of the class should be a static field. why should i make the returned instance of factory a static field?
the code is:
class DBHelper{
DBHelper._();
factory DBHelper()=>instance; // ->> cursor error
// static
// final
DBHelper instance=DBHelper._();
int number=2;
int fun()=>number;
}
I think you didn't quite get the purpose of factory methods. The example you've posted is the way of using singleton pattern in dart/flutter. It's, in my opinion the cleanest way of creating a singleton class.
Now the factory method can be used to to simplify the construction of objects and they don't have to return static fields at all. Here are a few examples:
class OneObject {
final int one;
final String two;
final double three;
OneObject(this.one, this.two, this.three);
factory OneObject.withoudTwo(int one, double three) {
return OneObject(one, "2", three);
}
factory OneObject.fromJson(Map<String, dynamic> aMap) {
return OneObject(aMap["one"], aMap["two"], aMap["three"]); // this is bad use of json parsing
}
}
In your case the DBHelper._(); is the actual constructor of the class and the _ makes it private and this allows you to create a factory method called DBHelper.();
To elaborate the answer a bit more, factory methods are similar to static methods and static methods can't access instance members of the class that they are declared on, they can access only static members. In your example, the instance property (without static) will be created only when a new instance of the DbHelper is created and because of that, returning it from a factory method is impossible because it's not available yet.
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.