Explore TypeDef In Dart & Fluter
In this blog, we will Explore TypeDef In Dart &Fluter. It tells you the best way to make and utilize typedef in Dart. It likewise works in Flutter and there’s a utilization example in your flutter applications.
In Dart, you can make a type alias to allude to a kind by utilizing typedef keywords. This article discloses how to make typedefs for function and non-function and how to utilize the made typedefs.
Table Of Contents::
How to Using typedef
for Functions
Using typedef
for Non-Functions
How to Using typedef
for Functions:
The typedef keyword was at first made in Dart 1 to allude to functions. In Dart 1, if you need to utilize a function as a variable, field, or boundary, you need to make a typedef first.
To utilize a type alias, you just need to relegate the function mark to a typedef. From that point onward, you can utilize the typedef as a variable, field, or boundary, as displayed in the model beneath.
typedef IntOperation<int> = int Function(int a, int b);
int processTwoInts (IntOperation<int> intOperation, int a, int b) {
return intOperation(a, b);
}
class MyClass {
IntOperation<int> intOperation;
MyClass(this.intOperation);
int doIntOperation(int a, int b) {
return this.intOperation(a, b);
}
}
void main() {
IntOperation<int> sumTwoNumbers = (int a, int b) => a + b;
print(sumTwoNumbers(2, 2));
print(processTwoInts(sumTwoNumbers, 2, 1));
MyClass myClass = MyClass(sumTwoNumbers);
print(myClass.doIntOperation(4, 4));
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
4
3
8
The following is another model where the function has a generic parameter type.
typedef Compare<T> = bool Function(T a, T b);
bool compareAsc(int a, int b) => a < b;
int compareAsc2(int a, int b) => a - b;
bool doComparison<T>(Compare<T> compare, T a, T b) {
assert(compare is Compare<T>);
return compare(a, b);
}
void main() {
print(compareAsc is Compare<int>);
print(compareAsc2 is Compare<int>);
doComparison(compareAsc, 1, 2);
doComparison(compareAsc2, 1, 2);
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
true
false
true
Since Dart 2, you can utilize function-type punctuation anyplace. Subsequently, it’s not important to make a typedef any longer. Flutter additionally expresses that the inline function type is liked. That is because individuals who read the code can see the function type straightforwardly. The following is what might be compared to the principal model without typedef.
int processTwoInts (int Function(int a, int b) intOperation, int a, int b) {
return intOperation(a, b);
}
class MyClass {
int Function(int a, int b) intOperation;
MyClass(this.intOperation);
int doIntOperation(int a, int b) {
return this.intOperation(a, b);
}
}
void main() {
int Function(int a, int b) sumTwoNumbers = (int a, int b) => a + b;
print(sumTwoNumbers(2, 2));
print(processTwoInts(sumTwoNumbers, 2, 1));
MyClass myClass = MyClass(sumTwoNumbers);
print(myClass.doIntOperation(4, 4));
}
Nonetheless, it very well may be valuable to make a typedef if the function is long and much of the time utilized.
Using typedef
for Non-Functions:
Before Dart 2.13, you can just utilize typedefs for function types. Since Dart 2.13, you can likewise utilize typedefs for making type aliases that allude to non-functions. The use is basically the same, you just need to allow the type to have alluded as a typedef.
In the first place, your Dart form should be version 2.13 or above. For Flutter, you need to utilize version 2.2 or above. You additionally need to refresh the base SDK form in pubspec. yaml to 2.13.0 and run bar get (for Dart) or flutter pub get
(for Flutter).
environment:
sdk: '>=2.13.0 <3.0.0'
For instance, you need to characterize a type that stores a list of integer data. For that reason, you can make a typedef whose type is List<int>. Afterward, if you need to characterize a variable for putting away an information show, you can utilize the typedef as the type. In the model underneath, we characterize a typedef considered DataList whose type is List<int>. As you can find in the code beneath, utilizing the typedef gives you similar conduct as utilizing the real type. You can straightforwardly relegate a list value and access the techniques and properties of List. If you check the runtimeType, you’ll get List<int> as the outcome.
typedef DataList = List<int>;
void main() {
DataList data = [50, 60];
data.add(100);
print('length: ${data.length}');
print('values: $data');
print('type: ${data.runtimeType}');
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
length: 3
values: [50,60,100]
type: List<int>
Not just like a variable, type aliases can likewise be utilized as a field, parameter, and return value of a technique.
typedef DataList = List<int>;
class MyClass {
DataList currentData;
MyClass({required this.currentData});
set data(DataList currentData) {
this.currentData = currentData;
}
ScoreList getMultipliedData(int multiplyFactor) {
DataList result = [];
currentData.forEach((element) {
result.add(element * multiplyFactor);
});
return result;
}
}
void main() {
MyClass myClass = MyClass(currentData: [50, 60, 70]);
myClass.data = [60, 70];
print(myClass.currentData);
print(myClass.getMultipliedData(3));
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
[70, 90]
[180, 210]
The following is another model. For instance, you need a type for storing request body whose keys and worth types can differ for each type. The Map<String, dynamic> data type is reasonable for that case. Be that as it may, rather than utilizing Map<String, dynamic> each time you need to proclaim a request body variable, you can make a typedef for the type.
typedef RequestBody = Map<String, dynamic>;
void main() {
final RequestBody requestBody1 = {
'type': 'BUY',
'itemId': 2,
'amount': 200,
};
final RequestBody requestBody2 = {
'type': 'CANCEL_BUY',
'orderId': '04567835',
};
print(requestBody1);
print(requestBody2);
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
{type:
BUY, itemId: 2, amount:
200}
CANCEL_BUY
{type:, orderId:
04567835}
You can also define a type alias that has a generic type parameter. The ValueList
type alias below has a generic type parameter T
. When you define a variable using the type alias, you can pass the generic type to use.
You can likewise characterize a type alias that has a generic type parameter. The NumberList type alias underneath has a nonexclusive type parameter T. At the point when you characterize a variable utilizing the type alias, you can pass the conventional type to utilize.
typedef NumberList<T> = List<T>;
void main() {
NumberList<String> numbers = ['1', '2', '3'];
numbers.add('4');
print('length: ${numbers.length}');
print('numbers: $numbers');
print('type: ${numbers.runtimeType}');
}
When we run the application, we ought to get the screen’s output like the underneath screen final output:
length: 4
numbers: [1, 2, 3, 4]
type: List<String>
Usage in Flutter:
The code beneath is a model for Flutter which makes a typedef for List<Widget> type.
import 'package:flutter/material.dart';
typedef WidgetList = List<Widget>;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: TypedefExample(),
debugShowCheckedModeBanner: false,
);
}
}
class TypedefExample extends StatelessWidget {
WidgetList buildMethod() {
return <Widget>[
const FlutterLogo(size: 60),
const Text('FlutterDevs.com', style: const TextStyle(color: Colors.blue, fontSize: 24)),
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: SizedBox(
width: double.infinity,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: buildMethod(),
),
),
);
}
}
Conclusion:
In the article, I have explained the basic structure of the TypeDef In Dart & Fluter; you can modify this code according to your choice. This was a small introduction to TypeDef In Dart & Fluter On User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information on Trying up the TypeDef In Dart & Fluter in your projects. That is how to make and utilize typedefs in Dart/Flutter. You need to allow a type or a function signature to a typedef. Then, at that point, the made typedef can be utilized as a variable, field, parameter, or return value of a strategy. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
Feel free to connect with us:
And read more articles from FlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.