Be sure to retweet brother for more Flutter posts at ~~~~

Ducafecat WeChat group

B stationhttps://space.bilibili.com/40…

The original

https://medium.com/flutterdev…

reference

  • https://dart.dev/guides/langu…

The body of the

In this blog we will explore Typedef In Dart & Fluter. It tells you the best way to use typedefs in DART. It also works in Flutter and has a utilitarian example in your Flutter application.

In Dart, you can use the typedef keyword to create a type alias to use a type. This article describes how to make functional and nonfunctional typedefs, and how to utilize the typedefs you make.

How do I use typedef for functions

The Typedef keyword was first 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 typedef first.

To use a type alias, simply demote the function tag to a typedef. From that point on, you can use typedef as a variable, field, or boundary, 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 screen output just like the final output at the bottom of the screen:

4
3
8

Here is another model of a function with 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 should get the screen output 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. It also expresses a preference for inline function types. This is because the individual reading the code can see the function type directly. Here’s what you can compare to a body model without typedefs.

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));
}

However, using typedef can be valuable if the function is long and is being utilized most of the time.

Use typedef for non-functions:

Prior to Dart 2.13, you could 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, your DART form should be version 2.13 or above. For Flutter, you need to utilize version 2.2 or above. In addition, you will 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: the SDK: "> = 2.13.0 < 3.0.0"

For example, you need to describe the type to store a list of integer data. For this reason, you can create a typedef of type List

. Later, if you need to describe a variable to place the information display, you can use a typedef as a type. In the following model, we characterize a typedef of type List

that is considered DataList. As you can find in the code below, using typedef gives you operations similar to those using real types. You can directly downgrade the List values and access the techniques and properties of the List. If you check the runtimeType, you will get List

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 screen output 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 fields, parameters, and return values for techniques.

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 screen output just like the final output at the bottom of the screen:

[70, 90]
[180, 210]

Here’s another pattern. For example, you need a type to store the body of the request, and the key and value types of that type may be different for each type. For this case, Map

data type is reasonable. However, each time you need to declare a request body variable, you can create a typedef for that type instead of using Map

.
,>
,>

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 screen output 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 you define a variable using a type alias, you can pass the generic type you want to use.

Similarly, you can represent a type alias with a generic type parameter. The following NumberList type alias has a non-exclusive type parameter t. When a variable is characterized by a type alias, a regular type can be passed 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 screen output 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 that defines a typedef for the 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 this article, I explained the basic structure of Typedefs in Dart & Fluter, and you can modify this code as you choose. This is a small introduction to TypeDef in Dart and Fluter on user interaction from my side, which works using Flutter.

I hope this blog has provided you with enough information to help you try out Typedef In Dart & Fluter In your project. This is how to make and utilize typedef in Dart/Flutter. You need to allow typedef type or function signatures. Then, at this point, you can use the generated typedef as a variable, field, parameter, or return value for the policy. So give it a try.


The elder brother of the © cat

https://ducafecat.tech/

https://github.com/ducafecat

The issue of

Open source

GetX Quick Start

https://github.com/ducafecat/…

News Client

https://github.com/ducafecat/…

Strapi manual translation

https://getstrapi.cn

WeChat discussion group Ducafecat

A series of collections

The translation

https://ducafecat.tech/catego…

The open source project

https://ducafecat.tech/catego…

DART programming language basics

https://space.bilibili.com/40…

Flutter Zero Basics Beginners

https://space.bilibili.com/40…

Flutter combat news client from scratch

https://space.bilibili.com/40…

Flutter component development

https://space.bilibili.com/40…

Flutter Bloc

https://space.bilibili.com/40…

Flutter Getx4

https://space.bilibili.com/40…

Docker Yapi

https://space.bilibili.com/40…