Content Developer II at Microsoft, working remotely in PA, TechBash conference organizer, former Microsoft MVP, Husband, Dad and Geek.
122463 stories
·
29 followers

Exploring Mixins in Dart — Flutter

1 Share

Mixins in Dart (Flutter) — And How it is different from Inheritance ?

Hello all!

Let’s talk about mixins today, with a question.

What is mixin? and how it is different from inheritance. If you know how it is different from inheritance then scroll to section 2 and check how to implement mixins :) if not we’ll break it down right here!

Section 1 : Let’s start with definition

mixin is a way to reuse code by allowing classes to inherit behaviours and properties from multiple sources.

Right ? this is what you’ll find mostly when you search about mixins. And most probably you’ll get confused it with inheritance like me :) . So, before we start with mixins it is very important to know about is-a relationship (inheritance) and has-a relationship (composition) .

So let us have some quick clarification on these concepts. have a look at this image

What you observe?

From the real-time example attached for reference. You can observe here that-

  • Samsung is-a Mobile
  • Samsung has-a Camera and has-a Bluetooth.

Now check out the following definitions to get more insight.

is-a Relationship : It can be defined as direct relationship between two class where one class (lets say Class B) is subclass of other class (lets say Class A). Which is called as INHERITANCE.

— — — — — — — — — — — — — — — — — — — — — — — — — — — — — — —

has-a Relationship: It can be defined as an association between two classes where one class (let’s say Class A) contains an instance of another class (let’s say Class B) as one of its members. This association allows Class A to have access to the functionalities and properties of Class B, thus known as COMPOSITION.

Finally let’s see how it looks programmatically.

*Attention: focus on comments*

//parent class
class Mobile {
}



//subclass or child class
//example of is-a relationship as Samsung extends Mobile
class Samsung extends Mobile {

//example of has-a relationship
Wifi wifi = Wifi();
Camera camera = Camera();

}

I Hope you’re now clear about is-a and has-a relationship.

Now let’s read the definition of mixin again, which I hope you already did.

mixin is a way to reuse code by allowing classes to inherit behaviours and properties from multiple sources, “without establishing a strict hierarchy of parent child relationship which is what inheritance (is-a relationship) does”.

So classes using mixin can inherit all properties and functions but cannot be termed as subclass.

why????

Because mixins establish a relationship similar to, but not exactly, a “has-a” relationship between a class and the functionalities provided by the mixin. It gains access to the methods and properties defined in the mixin.

However, the difference is the class itself doesn’t hold an instance of the mixin; rather, it just inherits it. There’s no strict hierarchy involved. So as it is not being bound by a strict hierarchy of parent-child relationships.

This flexibility allows classes to benefit from the functionalities provided by mixins without forming a direct “is-a relationship” with them.

Understood? If not, hang tight — we’ll dive into it in Section 2 and you’ll get it in no time!

Section 2 : Implementation of mixin

let’s dive now into how we can implement them in Dart and Flutter.

1.Declaring a Mixin : We declare a mixin using the mixin keyword followed by the mixin's name. Mixins can contain methods and properties.

mixin MixinLogger {

void logMessage(String message) {
print("MESSAGE: $message");
}

}

2.Using Mixins : To use a mixin in a class, we use the with keyword followed by the mixin's name. This allows the class to inherit the functionalities defined in the mixin.

class APIService with MixinLogger { 

void getPosts() {
try {
final response = http.get('https://www.example.com/posts');
} catch (Exception e) {
// Call mixin method
logMessage(e.toString());
}
}

}

Now!

void main(){
APIService apiService = APIService();

if(apiService.runtimeType is MixinLogger){
print("APIService is off type MixinLogger");
}
else{
print("APIService is not off type MixinLogger");
}
}

What will be the output?

If you don’t know and skipped section 1 , please have a look on it then.

So, The output will be APIService is not off type MixinLogger”.

why???? again same answer but this time i hope you will understand.

Because mixins establish a relationship similar to, but not exactly, a “has-a” relationship between a class and the functionalities provided by the mixin. It gains access to the methods and properties defined in the mixin.

However, the difference is the class itself doesn’t hold an instance of the mixin; rather, it just inherits it. There’s no strict hierarchy involved. So as it is not being bound by a strict hierarchy of parent-child relationships.

This flexibility allows classes to benefit from the functionalities provided by mixins without forming a direct “is-a relationship” with them.

Now let’s explore more features.

3. Features in mixin:

on keyword in mixin:

If you want to restrict your mixin to be used by only those classes which needs to subclass of your desired class then we should declare mixin class with on keyword.

mixin <mixinname> on <class_name_on_which_mixin_should_restricted>

*Attention: focus on comments*


mixin MixinDiscount on Product{

performDiscountOperation(double price,double discount){
//perform discount operations
}

}


class Product{

}

Here Discount mixin will be constrained and can only be used with class which is a subclass of product class Type.

//It will throw compile time error that
//Telvision can't be mixed as it should be implement Product
class Television with MixinDiscount{

}
//it will work as it adheres the rules
class Television extends Product with MixinDiscount{

void doSomeOperation(){
//you can call methods directly now
performDiscountOperation(1000,10);
}

}

inheriting multiple mixins :

Let’s declare two mixins MixinA and MixinB with one functions each.


mixin MixinA{

void functionA(){
print("function A");
}

}

mixin MixinB{

void functionB(){
print("function B");
}

}
class Consumer with MixinA,MixinB{

}

void main(){
final consumer = Consumer();
//Now consumer can be able to use both functions from mixin A and B
consumer.functionA();
consumer.functionB();
}

What if multiple mixins having same function signatures?

Dart got you covered :)

mixin MixinA {
void foo() {
print('A.foo');
}
}

mixin MixinB {
void foo() {
print('B.foo');
}
}

Now, let’s define a class C that uses both mixins A and B:

class ClassC with MixinA, MixinB {
// Class implementation...
}


void main(){
final c = ClassC();
c.foo(); // Output: B.foo
}

In this situation, the classC gets the foo() method from both mixins A and B But Dart has to decide which one to use since there’s a conflict. It picks the foo() method from the last mixin used, which is B. So, when we make an instance of the class C and call foo(), it calls the func from mixin B.

The programming languages that support multiple inheritance have complexity for this type of scenario, which is known as the diamond problem. But for Dart Easy, right? :)

That’s all for now.

Thanks for reading !!!

My First Ever Blog ! I Hope It Helped :)

Ibrahim Syed.


Exploring Mixins in Dart — Flutter was originally published in Flutter Community on Medium, where people are continuing the conversation by highlighting and responding to this story.

Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete

A Complete .NET Developer's Guide to Span with Stephen Toub

1 Share
From: dotnet
Duration: 1:02:48

Scott and Stephen are back with another entry in the Deep .NET series, this time looking deep at System.Span enabling the representation of contiguous regions of arbitrary memory, regardless of whether that memory is associated with a managed object, is provided by native code via interop, or is on the stack. And it does so while still providing safe access with performance characteristics like that of arrays. Let's go deep on Span.

Chapters:
00:00:00 Exploring the Impact and Evolution of Span in Software Engineering
00:03:09 Deep Dive into Assembly Code and its Translation
00:04:15 Exploring Methods to Disassemble and Analyze C# Function
00:05:43 Exploring the JIT Compiler and Assembly Code Optimization
00:12:03 Understanding Arrays and Pointers in Programming
00:16:46 Understanding Memory Management and Array Access in Programming
00:24:35 Discussing the Cost and Implementation of Memory Management Functions
00:26:23 Exploring the Intersection of Performance, Maintenance, and Interop in Programming
00:31:51 Understanding the Concept and Impact of Span in Computer Science
00:39:28 Discussion on Memory Protection and Immutability in Unix and Windows
00:45:59 Implementing and Understanding the Concept of Ref Functions in C#
00:51:08 Exploring JavaScript Optimal Notation and Memory Management
00:54:28 Exploring the Implementation and Functionality of Span in Programming
00:59:53 The Evolution and Impact of Span in .NET Development

Resources:
Documentation: https://learn.microsoft.com/dotnet/standard/memory-and-spans/

Connect with .NET:
Blog: https://aka.ms/dotnet/blog
Twitter: https://aka.ms/dotnet/twitter
TikTok: https://aka.ms/dotnet/tiktok
Mastodon: https://aka.ms/dotnet/mastodon
LinkedIn: https://aka.ms/dotnet/linkedin
Facebook: https://aka.ms/dotnet/facebook
Docs: https://learn.microsoft.com/dotnet
Forums: https://aka.ms/dotnet/forums
🙋‍♀️Q&A: https://aka.ms/dotnet-qa
👨‍🎓Microsoft Learn: https://aka.ms/learndotnet

#dotnet

Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete

EP172 RSA 2024: Separating AI Signal from Noise, SecOps Evolves, XDR Declines?

1 Share

Guests:

  • None

Topics:

  • What have we seen at RSA 2024?

  • Which buzzwords are rising (AI! AI! AI!) and which ones are falling (hi XDR)?

  • Is this really all about AI? Is this all marketing?

  • Security platforms or focused tools, who is winning at RSA?

  • Anything fun going on with SecOps?

  • Is cloud security still largely about CSPM?

  • Any interesting presentations spotted?

Resources:





Download audio: https://traffic.libsyn.com/secure/cloudsecuritypodcast/EP172_CloudSecPodcast_RSA2024.mp3?dest-id=2641814
Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete

Episode 163 - When and Why to HADR

1 Share

Guy and Eitan discuss the various High Availability and Disaster Recovery options available to us in Microsoft SQL Server, their main advantages, limitations, and when it's most suitable to use or not to use them.

Relevant links for further reading:





Download audio: https://traffic.libsyn.com/secure/madeirasqlserverradio/SQLServerRadio_Show163.mp3?dest-id=213904
Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete

Azure Announcements (Spring 2024)

1 Share

Microsoft Azure is constantly evolving, updating and changing environment. Sometimes this makes it difficult to follow all that happens around it. I will try to condense some of the announcements based on status – generally [...]

The post Azure Announcements (Spring 2024) appeared first on ITuziast.

Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete

Join the Uno Platform team at Microsoft Build 2024!

1 Share

Join the Uno Platform team at Microsoft Build 2024!

Whether you’re tuning into Microsoft Build 2024 from home or joining in Seattle, our team is excited to connect with you! 

If you’re in Seattle, be sure to visit the Microsoft expert booths and look for Martin and Steve from our team. They’re not just there to chat about all things .NET and help answer any questions you might have, they’re experts in their field. It’s the perfect chance to learn about the work we are doing at Uno Platform, pick their brains, and maybe even snag some Uno Platform gear. And if you see them around the venue, don’t hesitate to stop them and say hi! They love meeting new folks and hearing about the cool stuff everyone’s working on.

We’re genuinely excited to meet you, share stories, and give out some fun swag. It’s going to be a great time—hope to see you there!

Steve Bilogan

Steve Bilogan

Spot the bald guy in an Uno t-shirt—that’s me!

I’m a Senior Engineer and a maintainer of the Uno Platform project, including Uno Themes and Uno Toolkit. This year marks my inaugural recognition as a Microsoft MVP, and it’s my first time attending Build.

Find me in the .NET Developer Tools area:

May 21, 3:00 PM - 06:30 PM PDT
May 22, 3:00 PM - 06:30 PM PDT

Martin Zikmund

Martin Zikmund

Open-source developer and Microsoft MVP,
that contributes to Uno Platform. If you're there, let's connect! Look for the guy with the Uno Platform swag—so you won’t leave empty-handed!

Find me at the Windows developer productivity booth:

May 21, 3:00 PM - 06:30 PM PDT
May 23, 8:00 AM - 11:30 AM PDT

Get the insider

Come hang out with us on Discord for some behind-the-scenes action and offline session insights from Microsoft Build. It’s a great place to stay in the loop and meet other .NET developers who are just as passionate as you are.

Tags:

Related Posts

The post Join the Uno Platform team at Microsoft Build 2024! appeared first on Uno Platform.

Read the whole story
alvinashcraft
2 hours ago
reply
West Grove, PA
Share this story
Delete
Next Page of Stories