Dart's programming language beauty 4 super features

[external chain picture transfer failed. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-zevsndzx-1623715483769)( https://ducafecat.tech/2021/06/15/translation/the-beauty-of-the-flutters-programming-language-4-superb-features-of-dart/2021-06-15-07-58-44.png )]

Old iron remember to forward, brother old fellow will show more Flutter good text ~ ~ ~

Wechat Flutter Technology Group ducafecat

original text

https://reprom.io/the-beauty-of-the-flutters-programming-language-4-superb-features-of-dart

reference resources

  • https://dart.dev/codelabs/async-await
  • https://medium.com/flutter-community/dart-what-are-mixins-3a72344011f3
  • https://dart.dev/guides/language/language-tour
  • https://api.dart.dev/stable/2.13.1/dart-isolate/dart-isolate-library.html

text

One of the disadvantages I read most about when reading Flutter is the use of Dart programming language. It's not as mature as Kotlin, which is one of the most frequently mentioned arguments I've read. In my opinion (I admit this may be controversial), Dart is a great language. I won't change it for any other language when Flutter creates an application. I said it after Kotlin professionally creates android applications. By the way, it is also an elegant and beautiful language.

In this article, I intend to show four features of my favorite Dart programming language, in no specific order; Let's see how we can use this modern tool:

Null safety

Recently added in version 2.12 (included in fluent 2.0). In any modern language that pretends to be solid and efficient, air safety is a must. This is why Dart team has been committed to implementing sound null security, which means that we can have types that can be null and types that cannot be null. If we try to perform an unsafe operation later, we will get a coding error before the application is built:

// 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

Just as we have Promises in Javascript and Futures in Dart, async/await is the main keyword, which gives us developers a simple and powerful way to handle asynchronous operations:

With Futures, we can easily stop the current operation flow, wait for an asynchronous operation to complete, and then continue to work.

// 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
}

It should be pointed out that even if the async/await keyword is used, all operations are executed in the same thread. If we need specific performance requirements, we can use isolates to generate alternative threads.

There are many ways to define function parameters

In Dart, we have multiple options when defining function parameters:

// 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

One of the least popular trends in software development is reorganization rather than inheritance, which means using component like elements to add functionality to classes rather than inheriting from parent classes. This approach allows us to easily add encapsulated functionality without dealing with complex inheritance hierarchies.

For example, suppose you have a login logic that you might want to use in different locations in your application. You can use this logic to create a mixin and reuse it when needed:

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) {
        // ...
      },
    );
  }
}

The advantage here is that we can add as many mixin s as we like, rather than inheriting from a parent class only by using inheritance.

summary

These are just four of the many useful features Dart provides to developers. If you want to know more, I suggest you visit the Dart language tour, which explains every detail of the language in a very friendly way.

https://dart.dev/guides/language/language-tour

© Cat brother

https://ducafecat.tech/

https://github.com/ducafecat

Previous period

Open Source

GetX Quick Start

https://github.com/ducafecat/getx_quick_start

News client

https://github.com/ducafecat/flutter_learn_news

Translation of strapi manual

https://getstrapi.cn

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/

Fundamentals of Dart programming language

https://space.bilibili.com/404904528/channel/detail?cid=111585

Introduction to Flutter zero Foundation

https://space.bilibili.com/404904528/channel/detail?cid=123470

Actual combat of Flutter starts from scratch news client

https://space.bilibili.com/404904528/channel/detail?cid=106755

Fluent 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

Added by metalhead41 on Sun, 30 Jan 2022 05:22:04 +0200