Home Python C Language C ++ HTML 5 CSS Javascript Java Kotlin SQL DJango Bootstrap React.js R C# PHP ASP.Net Numpy Dart Pandas Digital Marketing

Learn Dart Iterators

Generics in Dart provide a way to create reusable components that can work with different types while maintaining type safety. They allow you to define classes, functions, and interfaces that can operate on a variety of data types without sacrificing type checking at compile time. Generics are especially useful for writing code that is more flexible, reusable, and maintainable.


Generics Classes You can create generic classes by using type parameters within angle brackets <>. These type parameters represent placeholders for actual types that will be provided when instances of the class are created.

class Box {
T value;
Box(this.value);
T getValue() => value;
} var integerBox = Box(10);
var stringBox = Box('Hello');



Generic Functions:: You can also define generic functions that work with different types. Similar to generic classes, you use type parameters within angle brackets <> to specify the types that the function can operate on.

T getLast(List list) {
if (list.isNotEmpty) {
return list.last;
} else {
throw Exception('List is empty');
}
}
var lastNumber = getLast([1, 2, 3, 4, 5]);
var lastName = getLast(['Alice', 'Bob', 'Charlie']);



Generic Interfaces:: Interfaces and abstract classes can also be made generic, allowing you to define type-safe contracts for classes that implement them.

abstract class Repository {
Future getById(int id);
Future save(T item);
}
class UserRepository implements Repository {
@override
Future getById(int id) {
// Implementation
}
@override
Future save(User user) {
// Implementation
} }


Type Inference with Generics In many cases, Dart's type inference system can infer the type parameters automatically based on the context, so you don't always need to explicitly specify them.

var integerBox = Box(10); // Type inference infers < int >
var lastNumber = getLast([1, 2, 3, 4, 5]); // Type inference infers < int >


Benefits of Generics
Type Safety : Helps catch type-related errors at compile time.
Code Reusability : Allows you to write reusable components that work with different types.
Abstraction : Encapsulates type-specific logic, promoting cleaner and more maintainable code.






Advertisement





Q3 Schools : India


Online Complier

HTML 5

Python

java

C++

C

JavaScript

Website Development

HTML

CSS

JavaScript

Python

SQL

Campus Learning

C

C#

java