乐趣区

关于flutter:Dart-的编程语言之美-4-个超级特性

老铁记得 转发,猫哥会出现更多 Flutter 好文~~~~

微信 Flutter 技术群 ducafecat

原文

https://reprom.io/the-beauty-…

参考

  • https://dart.dev/codelabs/asy…
  • https://medium.com/flutter-co…
  • https://dart.dev/guides/langu…
  • https://api.dart.dev/stable/2…

注释

在浏览 Flutter 时,我读到最多的毛病之一就是应用 Dart 编程语言。它还没有 Kotlin 那么成熟,这是我读到的最常被提及的论点之一。在我看来 (我抵赖这可能会引起争议),Dart 是一种平凡的语言,我不会在 Flutter 创立应用程序时为其余任何语言扭转它,我是在 Kotlin 业余地创立 android 应用程序之后说的,顺便说一句,这也是一种优雅而漂亮的语言。

在这篇文章中,我打算展现我最喜爱的 Dart 编程语言的 4 个个性,没有特定的程序; 让咱们看看咱们如何利用这个古代工具:

Null safety

最近在 2.12 版本中增加 (包含在 Flutter 2.0 中)。在任何伪装松软和高效的古代语言中,空平安都是必须的。这就是为什么 Dart 团队始终致力于实现声音 null 平安,这意味着咱们能够有能够为空的类型和不能为空的类型,如果咱们尝试在前面执行一个不平安的操作,咱们会在应用程序构建之前失去一个编译谬误:

// This is a String that can be null
String? nullVar;

// This String cannot be null, the compiler forces me
// to set it a value because of its non-nullable nature.
String nonNullVar = 'I am not null';

// Alternatively, I can specify that the value will be
// set later, but the property continues to be non-nullable.
late String lateNonNullVar;

// If I want to call a method on an instance of a type
// that can be null, I need first to do a runtime check that
// its value is not null.
if (nullVar != null) {nonNullVar.toLowerCase();
}

// Or call it using the '?' operator, which means that the
// method will only be called if the instance is not null:
nullVar?.toLowerCase();

// If the type is not nullable I can safely call any
// method on it directly.
nonNullVar.toLowerCase();

// Always remember to initialize late vars, or you
// will get an exception when trying to access its members.
lateNonNullVar = 'some value';
lateNonNullVar.toLowerCase();

Async / await

就像在 Javascript 中咱们有 Promises,在 Dart 中咱们有 Futures,其中 async/await 是次要的关键词,这给了咱们开发者一个简略而弱小的办法来解决异步操作:

应用 Futures,咱们能够轻松地进行以后操作流,期待某个异步操作实现,而后持续工作。

// To specify that a function will perform an asynchronous
// operation (like doing a network request or reading from
// a database) we mark it with the 'async' keyword:
asyncFunction() async {// ...}

// Use the 'await' keyword to stop the flow until the function
// has completed its task:
await asyncFunction();

// You must declare a function as 'async' if it contains
// calls to other async functions:
main() async {await asyncFunction();
}

// If the async function returns a value, wrap it within
// a Future. For instance, the following function
// would do a network call and return its result:
Future<NetworkResult> doNetworkCall() async {// ...}

final result = await doNetworkCall();

// But what if the network request fails and an exception
// is thrown? Just wrap the call in a try/catch block:
late NetworkResult result;
try {result = await doNetworkCall();
} on NetworkException catch (e) {// Handle error}

须要指出的是,即便应用 async/await 关键字,所有的操作都是在同一个线程中执行的,如果咱们须要具体的性能要求,咱们能够应用 isolates 产生代替线程。

定义函数参数的多种办法

在 Dart 中,咱们在定义函数参数时有多个选项:

// You can define mandatory parameters as you do in
// many other languages, specifying their type and setting a label:
functionWithMandatoryParameters(String someString, int someNumber) {// ...}

// You are forced to send the defined parameters
// when using the function:
functionWithMandatoryParameters('some_string', 46);

// You can however specify that the parameters are optional:
// (note that the type must be defined as nullable, precisely because
// there's no guarantee that the caller will send a value)
functionWithOptionalParams({String? optionalString, int? optionalNumber}) {// ...}

// You can call this function without sending any values,
// or specifying a value for an optional parameter with its label:
functionWithOptionalParams();
functionWithOptionalParams(optionalString: 'some_string');
functionWithOptionalParams(optionalString: 'some_string', optionalNumber: 46);

// When defining optional parameters, you can set a default value
// that will be used in case that there is no value sent by the caller:
functionWithDefaultValue({String someString = 'default'}) {// ...}

// The value of someString is 'default'
functionWithDefaultValue();
// The value of someString is 'some_string'
functionWithDefaultValue(someString: 'some_string');

// Lastly, you can even define mandatory named parameters with the
// 'required' keyword, this is useful to enhance code readability.
createUser(
  {required String username,
  required String name,
  required String surname,
  required String address,
  required String city,
  required String country}) {// ...}

createUser(
  username: 'Ghost',
  name: 'John',
  surname: 'Doe',
  address: '3590  Mill Street',
  city: 'Beaver',
  country: 'US');

Composition with mixins

软件开发中最不风行的趋势之一是重组而不是继承,这意味着应用相似组件的元素向类增加性能,而不是从父类继承。这种办法容许咱们轻松地增加封装的性能,而无需解决简单的继承层次结构。

例如,假如您有一个登录逻辑,您可能心愿在应用程序中的不同地位应用它。您能够应用这个逻辑创立一个组件 (mixin),而后在须要时重用它:

abstract class AuthUtils {Future<User> login() async {
    // Here we can add the login logic that will later be reused
    // in any class that ads this mixin.
  }
}

class LoginPage extends StatefulWidget {LoginPage({Key? key}) : super(key: key);

  @override
  _LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> with AuthUtils {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder<User>(future: login(), // Calling the mixin function
      builder: (BuildContext context, AsyncSnapshot<User> snapshot) {// ...},
    );
  }
}

这里的长处是,咱们能够得心应手地增加任意多的 mixin,而不是仅通过应用继承从一个父类继承。

总结

这些只是 Dart 提供给开发者的多个有用个性中的 4 个。如果你想理解更多,我倡议你去参观 Dart 语言之旅,它以一种十分敌对的形式解释了这门语言的每一个细节。

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


© 猫哥

https://ducafecat.tech/

https://github.com/ducafecat

往期

开源

GetX Quick Start

https://github.com/ducafecat/…

新闻客户端

https://github.com/ducafecat/…

strapi 手册译文

https://getstrapi.cn

微信探讨群 ducafecat

系列汇合

译文

https://ducafecat.tech/catego…

开源我的项目

https://ducafecat.tech/catego…

Dart 编程语言根底

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

Flutter 零根底入门

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

Flutter 实战从零开始 新闻客户端

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

Flutter 组件开发

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…

退出移动版