Why Flutter favour composition over inheritence? [duplicate] - flutter

This question already has answers here:
Subclass a class that extends StatelessWidget or StatefulWidget class
(5 answers)
Closed 1 year ago.
Some places on internet, i read RaisedButton uses composition like text widget that contain other properties to set Text? My question is what does it mean?What happens if use inheritence instead of composition?
Here is code:
RaisedButton(
child: Text("Decrement Counter"),
onPressed: () => _decrementCounter(),),

Flutter prefer composition over inheritance because it is easy to manage since it represent "" has a " relationship. Consider this
Class person{
String name;
Address add;
}
In above scenario , it is better practice to make separate class for address because it contain multiple information like house no,city,country postal code etc.if you place all the information inside person class this should work but not in a better way.

Related

How to Handle Multiple, Related State Management Classes in Flutter

I have a Flutter app that uses an SQLite database that has lots of inter-dependent tables. So far I have used Provider to create a class for each table in my database. The classes rely on each other and need to know when some of the others update.
I have added all 23 of my providers to main.dart using MultiProvider. I'm finding that Provider won't allow me to access ClassA from ClassB which is a deal-breaker.
I am considering a few options:
Option 1 - Riverpod
This tool allows me to make different groups of data aware of each other, but the downside is a lot of extra code. You have to create an entire StateNotifierProvider just to watch a single list of data. The learning curve feels steep, too.
//One of these for every single reactive data list + other provider types for other data types
class ClassANotifier extends StateNotifier<List<DataType1>> {
ClassANotifier(): super([]);
...
}
Option 2 - GetX
There is an enormous amount of debate about GetX, but I'm trying to ignore all of that. It seems that GetX controllers allow me to reference other controllers anywhere I want. It appears this would solve my problem (but potentially bring unwanted side-effects that the internet is raging about).
class ControllerA extends GetxController {
var controllerB = Get.put(ControllerB());
}
class ControllerB extends GetxController {
...
}
Option 3 - Single, Monolithic Provider Class
I recently learned that I can break a Dart class up across multiple files like this:
//=== class_a.dart ===
part 'class_b.dart';
class ClassA with ChangeNotifier {
...
}
And then in the other files:
//=== class_b.dart ===
part of 'class_a.dart';
extension ClassB on ClassA{
...
}
This would approach would allow me to use Provider to have a single class I put in my widgets, and I can access any part of my data structure across my app. I would have to be careful to name things clearly, but otherwise it seems like it could work.
Is there another way to handle lots of inter-dependent data like this in my app's state?
GetX is talked about a lot, but when you work with it, you fall in love. I use it in all my projects, they are not projects for large companies, but for many screens (50 to 100).
It's very simple and its learning curve is smooth!
I use it and will continue to use it!!!
Screen A -> Screen B -> Screen C (in B and C you have access to A controller) when close A, GetX down A Controller!! (this optimizes memory usage!!)

Way to efficiently create multiple same widgets with different text

We are trying to create a language learning app as a project in flutter.
One level would have same widget tree just repeated multiple times with different questions and answers to be chosen.
Once correct answer is chosen it takes you to new question.
Any ideas on how we can efficiently create multiple of same widgets with different text inside?
You can extract your widget as Widget with text parameter. So just use the widget anywhere and pass text argument now you will get same widget with different text.
Generally speaking, if you want to create multiple objects/widgets from the same class with slight changes, all you need to do is to create a constructor and pass some data to it.
Here's an example:
Class MyText extends StatelessWidget {
final String text;
MyText({this.text});
// your build method that returns the text goes here..
}
To use:
MyText('Hello');
MyText('World');
Good luck building your game!

Does anyone know if it is possible to extend a flutter widget?

Is it possible to extend a widget? take for instance the CalendarDatePicker widget. I like the existing features but I want to be able to extend it.
I want to be able to have a little dot under each day that has some events whether it is just one or multiple events. If a day doesn't have any events, then nothing needs to show under that day. Events would be coming from a firebase Firestore.
The reasons are:
I like the CalendarDatePicker and I prefer not having to install a new package. I see people are using Table_Calendar. It is nice but I am trying to reuse leverage what is already there and stay away from installing too many packages.
I'd prefer not to design one from scratch when there is one that already does 98% of what needs to get done.
Thanks
You can extend widgets and override its properties and methods with extends keyword (see docs). It is simple OOP inheritance. But anyway you should fully override build method to complement existing UI. Do it, copy existing code from CalendarDatePicker build method to you custom class build method and update this code as you wish:
class CustomDatePicker extends CalendarDatePicker {
const CustomDatePicker({
Key? key,
// here you can use constructor properties that you need
// and pass them to superclass constructor
}) : super(...);
#override
Widget build(BuildContext context) {
// use code from CalendarDatePicker build method
// and update it as you wish
}
}

Difference between getter and a regular method in Dart

I'm just getting my feet wet with the BLoC architecture of Flutter. Here, I wish to create a Bloc class, which will help me to convert the user input in the form of stream data. To do that task, let's say that first of all I create an instance of Bloc class with the name email and then,
make use of snippet 0 & then call email.emailController.sink.add(some_string)
or, make use of snippet 1 and then call email.streamEmail(some_string)
or, make use of snippet 2 code and then call email.streamEmail(some_string)
to add a string input to the stream
Code snippets:
//Snippet 0 : w/o any `method`
class Bloc{
final emailController = StreamController<String>();
}
//Snippet 1 : using regular 'method'
class Bloc{
final emailController = StreamController<String>();
void streamEmail(String value) => emailController.sink.add(value);
}
//Snippet 2 : using 'get' based 'method'
class Bloc{
final emailController = StreamController<String>();
Function(String) get streamEmail => emailController.sink.add;
}
I learned that making use of snippet 1 or 2 is a rather better to approach, in terms of code readability.
I know that snippet 1& 2 are just 2 different ways of doing the same thing. However, I'm not clear about the differences that snippet 2 brings in, by making use of the getter method.
From A tour of the Dart language,
Getters and setters are special methods that provide read and write access to an object’s properties.
At the moment, the only thing I understand about getters is that they represent an alternative approach to define methods within a class. So, to be precise my questions are :
Does usage of a getter method lead to enhancement or drop in-app. performance?
When & why should I be using snippet 2 type class definitions instead of snippet 1?
Does usage of a getter method lead enhancement or drop in app. performance?
No, using getter/setter instead of methods does not impact performance.
When & why should I be using snippet 2 type class definitions instead of snippet 1?
When to use getters/setters is a question about taste and some developers are more likely to use them than others. I guess a general design goal should be that getters/setters acts like normal properties on an object and should therefore not make any additional unknown behavior than getting/setting a property. (e.g. get a property of a objects will end up saving some files to the file system).
In your example I would go with snippet 1 (and maybe with a different name of the method) since your example is not really a good use case of using properties. Snippet 2 seems like a forced clever attempt to make use a getter which ends up being a little weird since the getter ends up returning a Function.
But again, this is a question about taste and I am sure there are some developers which would go with snippet 2.

prevent empty constructors from #Immutable annotation

I use groovy and like the #Immutable annotation. The problem is, that this annotation does not only create constructors with the specified class fields, but also creates an empty constructor and allows the fields to partly stay null (or take a default value). I want to prevent this.
Example:
#Immutable class User { int age}
can be called like
User jasmin = new User(30)
println "I am ${jasmin.age} years old" // I am 30 years old
but also like
User james = new User() //Uhoh, I have no age
println "I am ${james.age} years old" // I am 0 years old - maybe not expected
My question is therefor: are there any annotations or other ways that prevent calling the empty constructor? Possibly throwing an exception when there is no age passed (or null passed for it) at runtime. Bonus points if I get eclipse IDE support so that an empty constructor call is complained by eclipse at compile time.
I did not find something like #NotNull for groovy, but for java i found different annotations as the ones in this question. Would using one of these a good idea? How to decide? Or is it better to write my own custom annotation - and can I get IDE help by doing that?
I agree with you; there should be an option in the #Immutable attribute to prevent the generation of the default constructor.
As far as a workaround, this probably isn't as elegant as you'd like, but I'm throwing this out there. If you create a mutable super type without a default constructor, you could extend it with an #Immutable version. For example:
import groovy.transform.*
class MutableUser {
int age
// defining an explicit constructor suppresses implicit no-args constructor
MutableUser(int age) {
this.age = age
}
}
#Immutable
#InheritConstructors
class User extends MutableUser {
}
User jasmin = new User() // results in java.lang.NoSuchMethodError
But overall, this seems like an unnecessary amount of boilerplate just to suppress a no-arg constructor.