Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~
WeChat group ducafecat
b station https://space.bilibili.com/404904528
original
https://medium.com/flutterdevs/explore-typedef-in-dart-fluter-6dd102fdf5f9
refer to
text
In this blog, we will explore TypeDef In Dart & Fluter. It tells you the best way to use typedef in Dart. It also works in Flutter and has an example of use in your Flutter application.
In Dart, you can use the typedef keyword to create type aliases to use a certain type. This article describes how to make functional and non-functional typedefs, and how to use the created typedefs.
How to use typedef for functions
The Typedef keyword was originally used in Dart 1 to imply functions. In Dart 1, if you need to use a function as a variable, field, or boundary, you need to use a typedef first.
To use type aliases, just downgrade the function tag to typedef. From then on, you can use typedefs as variables, fields, or boundaries, as shown in the model below.
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 should get the output of the screen, just like the final output at the bottom of the screen:
4
3
8
Below is another model where the function has generic parameter types.
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 should get the output of the screen, just like the final output at the bottom of the screen:
true
false
true
Since Dart 2, you can use function type punctuation everywhere. Therefore, it is not important to use typedef again. In addition, I like the inline function type. This is because individuals who read the code can directly see the function type. The following is the content that can be compared with the subject 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, if the function is long and is used most of the time, it is valuable to use a typedef.
Use typedef for Non-Functions:
Before Dart 2.13, you can use typedef to handle function types. Since Dart 2.13, you can also use typedefs to create type aliases that imply non-functions. The usage is basically the same, you only need to allow the type as a typedef.
First of all, your Dart table should be version 2.13 or above. For Flutter, you need to use version 2.2 or above. In addition, you also need to refresh the basic 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 example, you need to describe the type of stored integer data list. For this reason, you can create a typedef whose type is List <int>
. Later, if you need to describe the variable used to place the information display, you can use typedef as the type. In the following model, we describe a List <int>
which is considered to be a DataList. As you can find in the code below, using typedef can provide you with operations similar to using actual types. You can directly downgrade the list value and access the technology and attributes of the List. If you check the runtimeType, you will get List <int>
as the result.
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 should get the output of the screen, just like the final output at the bottom of the screen:
length: 3
values: [50,60,100]
type: List<int>
Unlike variables, type aliases can also be used as technical fields, parameters, and return values.
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 should get the output of the screen, just like the final output at the bottom of the screen:
[70, 90]
[180, 210]
Here is another mode. For example, you need a type to store the request body, and the key and value types of this type may be different for each type. In this case, Map <String,dynamic> data type
is reasonable. Nevertheless, every time you need to declare a request body variable, you can create a typedef for that type instead of using Map <String,dynamic>
.
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 should get the output of the screen, just like the final output at the bottom of the screen:
{type: BUY, itemId: 2, amount: 200}
{type: CANCEL_BUY, orderId: 04567835}
You can also define type aliases with generic type parameters. The following ValueList type alias has a generic type parameter t. When using a type alias to define a variable, you can pass the generic type to be used.
Similarly, you can express type aliases with generic type parameters. The following alias of the NumberList type has a non-exclusive type parameter t. When using type aliases to characterize variables, you can pass regular types for use.
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 should get the output of the screen, just like the final output at the bottom of the screen:
length: 4
numbers: [1, 2, 3, 4]
type: List<String>
Usage in Flutter
The following code is a Flutter model, which defines a typedef List <widget>
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 this article, I explained the basic structure of TypeDef in Dart & Fluter, you can modify this code according to your choice. This is a small introduction to TypeDef's user interaction in Dart and Fluter. From my side, it works using Flutter.
I hope this blog can provide you with enough information to help you try TypeDef In Dart & Fluter in your projects. This is how to make and use typedefs in Dart/Flutter. You need to allow typedef types or function signatures. Then, at this point, the generated typedef can be used as a variable, field, parameter, or return value of the strategy. So please try it.
© Cat brother
Past
Open source
GetX Quick Start
https://github.com/ducafecat/getx_quick_start
News client
https://github.com/ducafecat/flutter_learn_news
strapi manual translation
WeChat discussion group ducafecat
Series collection
Translation
https://ducafecat.tech/categories/%E8%AF%91%E6%96%87/
Open source project
https://ducafecat.tech/categories/%E5%BC%80%E6%BA%90/
Dart programming language basics
https://space.bilibili.com/404904528/channel/detail?cid=111585
Getting started with Flutter zero foundation
https://space.bilibili.com/404904528/channel/detail?cid=123470
Flutter actual combat from scratch news client
https://space.bilibili.com/404904528/channel/detail?cid=106755
Flutter component development
https://space.bilibili.com/404904528/channel/detail?cid=144262
Flutter Bloc
https://space.bilibili.com/404904528/channel/detail?cid=177519
Flutter Getx4
https://space.bilibili.com/404904528/channel/detail?cid=177514
Docker Yapi
https://space.bilibili.com/404904528/channel/detail?cid=130578
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。