当前位置:网站首页>Class extension and optional type extension of dart
Class extension and optional type extension of dart
2022-06-28 23:12:00 【One leaf floating boat】
extends
Inherit . Dart No more inheritance in . The root class is Object.
abstract class StatefulWidget extends Widget
abstract class StatelessWidget extends Widget
mixin ( With)
Mix in (mixin). Using a function of another class in a non inherited way .
//flutter Mixed classes are used in
abstract class Diagnosticable with DiagnosticableMixin Example
class A {
a(){
print("this is a function!");
}
}
mixin aa {
aaFunction(){
print("this is aa function! ha ha !");
}
}
class Aa with aa,A
{
}
// call
Aa()
..a()
..aaFunction();
implements
Realization .dart Not in it interface keyword .implements And OC Of delegate similar .
eg :flutter Inside Element and List. BuildContext and Iterable All abstract classes (abstract) Just providing interfaces , And then in implements Class to implement .Flutter Used in implements Class
abstract class Element extends DiagnosticableTree implements BuildContext
// take BuildContext The members of this class are regarded as the definitions of interfaces
abstract class List<E> implements EfficientLengthIterable<E>
abstract class EfficientLengthIterable<T> extends Iterable<T>// It implements fast traversal and other methods
Realization implements Class before the method @override
// Element What's achieved in BuildContext Methods
@override
InheritedWidget inheritFromElement(InheritedElement ancestor, { Object aspect }) {
assert(ancestor != null);
_dependencies ??= HashSet<InheritedElement>();
_dependencies.add(ancestor);
ancestor.updateDependencies(this, aspect);
return ancestor.widget;
}
class AB implements B , be A Must be realized in B All the methods in , Even if B Class to implement this method .Missing concrete implementation of B
and mixin Class does not have to implement , If it is implemented, call... First ABclass Implementation method in
class A {
a(){
print("this is a function!");
}
}
mixin aa {
aaFunction(){
print("this is aa function! ha ha !");
}
}
class B {
b(){
print("this is b ! b B");
}
bB(){
print("this B class bB Function !");
}
}
abstract class BB {
bb();
}
class AB with aa,A implements BB, B
{
@override
a() {
print("this is AB class a Function !");
}
@override
bb() {
print("this is Aa class bb Function !");
}
@override
b() {
print("this is Aa class b Function !");
}
@override
bB() {
print("this is Aa class bB Function !");
}
}
The results
AB()
..a()
..aaFunction()
..b()
..bb();
// Print
I/flutter (29103): this is AB class a Function !
I/flutter (29103): this is aa mixin function! ha ha !
I/flutter (29103): this is Aa class b Function !
I/flutter (29103): this is Aa class bb Function !
The above three relationships can exist at the same time , But there is a sequence : extends -> with (mixin) -> implements
<>
Generic . For the specified generic type
eg. Let's subclass the declaration State The method of class is
class TabBarState extends State <TableBarPage>
///<TableBarPage> indicate TabBarState Parent class of State It's used to show TableBarPage The state of
And it is used for List Generics in , And OC The usage is the same in
List<Widget> pages = List<Widget>();///List Li Wei Widget Or its subclass
use Extension Extend the class
In general, you need to extend a class , You need to inherit this class , This is in most cases java Or something to do in other object-oriented languages .
But sometimes extension classes are not particularly easy to use , First, in some languages , Some classes are not allowed to be extended . Even if it can be extended , But the extended class is a new class , Instead of the original parent class , Therefore, there may be some type conversion problems in the process of use .
So in dart How to solve this problem in ?
dart in extension Use (2.7 New features )
dart stay 2.7 after , Introduced extension, Used to extend the methods of the class .
How to expand ? Let's take an example .
We can convert the string to int, By calling int Of parse Method , As shown below :
int.parse('18')But by int Class is usually less intuitive , We hope to be able to String Class toInt Methods , Can be called directly , Convert a string to int.
'18'.toInt()But unfortunately ,String It didn't provide toInt Methods , So we can pass extension Come on String Expand :
extension StringToNumber on String {
int toInt() {
return int.parse(this);
}
// ···
}If the name of this file is string_to_number.dart, Then we can use :
import 'string_to_number.dart';
// ···
print('18'.parseInt());
dart The most convenient method extension in is , You just introduce the corresponding lib, I don't even know when I'm using lib An extension of .
Of course , Not all classes can be used extention Expand . such as dynamic Type cannot be extended .
But use var type , As long as the type can be inferred , Then you can use it extention Expand .
API Conflict
Since you can be right lib Expand , Then it's possible that API Conflict situation . So how to solve API What about the conflict ?
For example, we need to use two lib Extension files ,extention1.dart and extention2.dart. But both extension files define parseInt Method pair String Expand .
If quoted at the same time , There will be problems .
You can use it show perhaps hide To limit which method in the extension file is used .
import 'extention1.dart';
import 'extention2.dart' hide StringToNumber2;
print('18'.parseInt());There is also a case where the display calls extension, As shown below :
import 'extention1.dart';
import 'extention2.dart';
print(StringToNumber('18').parseInt());
print(StringToNumber2('18').parseInt());adopt extention To distinguish them by their names .
If two extention If your name is the same , So you can go through prefix To distinguish :
import 'extention1.dart';
import 'extention2.dart' as ext2;
print(StringToNumber('18').parseInt());
print(ext2.StringToNumber('18').parseInt());extention The implementation of the
Implementing extensions is simple , The implementation syntax is as follows :
extension <extension name> on <type> {
(<member definition>)*
}Here is an extension String Example :
extension NumberParsing on String {
int parseInt() {
return int.parse(this);
}
double parseDouble() {
return double.parse(this);
}
}
extension You can also extend generic parameters :
extension MyFancyList<T> on List<T> {
int get doubleLength => length * 2;
List<T> operator -() => reversed.toList();
List<List<T>> split(int at) => [sublist(0, at), sublist(at)];
}The above implementation is right List Expand , Added getter, Operators, and split Method .
Examples of optional type extensions :
final String? a = null;
DDLog(a.runtimeType); // Null
DDLog(a.or(() => "456")); // 456
DDLog(a.or((){
return "111";
})); // 111
extension GetDynamicExt<T> on T {
/// Returns an optional value or `else` The value returned by the closure
/// for example . nullable.or(else: {
/// ... code
/// })
T or(T Function() block) {
return this ?? block();
}
}
边栏推荐
- Powerful open source API interface visual management platform Yapi
- Fanuc robot_ Introduction to Karel programming (2)_ Usage of general IO signal
- Deep virtual memory (VM)
- 全面掌握const的用法《一》
- Is the account opening of Guosheng securities really safe and reliable
- O & M troubleshooting - use hcache plug-in to troubleshoot excessive buffer/cache occupancy
- 云计算的迷路者
- C interview questions_ 20220627 record
- 2022 PMP project management examination agile knowledge points (4)
- Online sql to htmltable tool
猜你喜欢

With a monthly salary of 60000 yuan, such people began to be robbed after the Internet "reduced costs and increased efficiency"
![[word Tutorial Series Part 1] how to remove arrows in word tables](/img/c7/dc57002b0e9d433c4dfac15d53713d.png)
[word Tutorial Series Part 1] how to remove arrows in word tables

超级工厂里的生意图鉴

深入虚拟内存(Virtual Memory,VM)

leetCode-栈类型详解

Business atlas in super factory

What is the difference between WMS warehouse management system and ERP

Powerful open source API interface visual management platform Yapi

邂逅阿维塔 11:强产品力下久违的新鲜感

C interview questions_ 20220627 record
随机推荐
Realization of 2D code generation in micro build low code
【Word 教程系列第 2 篇】Word 中如何设置每页的表格都有表头
Wechat red envelope cover making tutorial and use guide with link jump
O & M troubleshooting - use hcache plug-in to troubleshoot excessive buffer/cache occupancy
机器学习6-决策树
LeCun预言AGI:大模型和强化学习都是斜道!我的世界模型才是新路
Differences among CPU, GPU, TPU and NPU
DBNN实验进展
frameworks/base/core/res/res/values/symbols.xml:3915: error: no definition for declared symbol解决办法
Lecun predicts AgI: big model and reinforcement learning are both ramps! My world model is the new way
2022-06-28:以下golang代码输出什么?A:true;B:false;C:panic;D:编译失败。 package main import “fm
Deep virtual memory (VM)
Business atlas in super factory
[数学建模]Matlab非线性规划之fmincon()函数
C interview questions_ 20220627 record
见丰知夏|国漫鼻祖丰子恺,数字藏品独家发售
Complex nested object pool (4) -- manage the object pool of multi class instances and multi-stage instances
See fengzhixia | FENGZikai, the originator of Guoman, for exclusive sale of Digital Collections
微搭低代码中实现二维码生成
Keil project, RTT cannot print after too many programs are written