Old iron remember to forward, Brother Mao will present more Flutter good articles~~~~
WeChat Flutter Technology Group ducafecat
original
https://reprom.io/the-beauty-of-the-flutters-programming-language-4-superb-features-of-dart
reference
- 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
When reading Flutter, one of the shortcomings I read most is the use of the Dart programming language. It is not as mature as Kotlin, and this is one of the most frequently mentioned arguments I read. In my opinion (I admit that this may be controversial), Dart is a great language, I will not change it for any other languages when creating an application in Flutter, I said after creating an android application professionally in Kotlin Yes, by the way, this is also an elegant and beautiful language.
In this article, I intend to show 4 features of my favorite Dart programming language, in no particular order; let's see how we can use this modern tool:
Null safety
Recently added in version 2.12 (included in Flutter 2.0). In any modern language that pretends to be solid and efficient, air safety is a must. This is why the Dart team has been working to achieve sound null safety, which means that we can have nullable types and non-nullable types. If we try to perform an unsafe operation later, we will do it before the application is built. Get a compilation error:
// 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 like in Javascript we have Promises, in Dart we have Futures, where async/await are the main keywords, which gives us developers a simple and powerful way to handle asynchronous operations:
Using 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 keywords are used, all operations are performed in the same thread. If we need specific performance requirements, we can use isolates to generate alternative threads.
Multiple 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 a class instead of inheriting from a parent class. This approach allows us to easily add encapsulated functionality without having to deal with complex inheritance hierarchies.
For example, suppose you have a login logic, and you may want to use it in different places in the application. You can use this logic to create a mixin, and then 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 mixins as we want, instead of just inheriting from a parent class by using inheritance.
to sum up
These are just 4 of the many useful features that Dart provides to developers. If you want to learn 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
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) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。