• Top 7 Dart Tips and Tricks for Cleaner Flutter Apps
  • Original author: The Educative Team
  • The Nuggets translation Project
  • Permanent link to this article: github.com/xitu/gold-m…
  • Translator: Hoarfroster
  • Proofreader: 5Reasons, greycodee

Dart is a client-optimized programming language designed to quickly build mobile, desktop, and server applications. Dart was developed by Google and works with Flutter, Google’s cross-platform framework. With Flutter and Dart, we can build applications with a smooth UI and native performance.

Today, we’ve rounded up and shared seven of the most useful Dart tips we think will help you improve your application development. You can use these techniques to write clean code and take advantage of many of the features that Dart offers.

Quick Overview – Tips and tricks:

  1. Use anonymous functions as arguments
  2. usecallMethods allow a class to be called as if it were a function
  3. use.entriesLet’s walk over a map
  4. How do I use getters and setters
  5. withSetStore unique values
  6. Use Inspect
  7. Use sync and async generators

1. Use anonymous functions as arguments

In the Dart language, you can pass functions as arguments to other functions, and the Dart language itself supports anonymous functions that can be called without naming.

The following is an example of using anonymous functions in Dart. In this case, we pass an anonymous cubing function to the built-in method forEach to try to get the cube of each item in the list array.

main() {
  var list = [1.2.3];
  list.forEach((item) {
    print(item * item * item);
  });
}
Copy the code

2. UsecallMethods allow a class to be called as if it were a function

Using the Dart language, we can construct a callable class that allows instances of the class to be called as functions. We can do this with the call() method, as shown in the following syntax:

class class_name {...// class 

  return_type call ( parameters ) {
  	... // Call this function content}}Copy the code

Let’s look at an example:

class EducativeIntro {

  // Define the call method
  String call(String a, String b, String c) => 'Welcome to $a$b$c';
}

/ / the main function
void main() {
  var educative_input = EducativeIntro();

  // Call this class with an instance
  var educative_output = educative_input('our '.'Dart '.'tutorial');

  print(educative_output);
}
Copy the code

Note: Dart does not support multiple callable methods

Use 3..entriesLet’s walk over a map

In Dart we can use the Entries () method to null safely traverse a map. Suppose we now have a map to track the amount of money spent on different products (which we usually do! Operator traverses the map) :

for (var key in moneySpent.keys) {
  finalvalue = moneySpent[key]! ;print('$key: $value');
}
Copy the code

We can improve this code and use loops to make it more secure. When traversing the entries variable, we can null-safe access key-value pairs.

for (var entry in moneySpent.entries) {
  // Use key-value pairs to do something
  print('${entry.key}: ${entry.value}');
}
Copy the code

4. How to use getters and setters

Getters and setters are a pair of special methods that can read and write properties of an object. Our calls to getters and setters are like instance variables: the dot operator (.). This is followed by the name of the function.

A getter is a function used to get the value of an object property, defined using the get keyword.

In the example below, we create a getter function at line 13 that returns the value of the name property of the current instance. And in line 21, we call the getter function, and the output should be Sarah.

class Person {
  String name;
  String gender;
  int age;

  Person(this.name, this.gender, this.age);

  Person.newBorn(){
    this.age = 0;
  }

	// Getfunction to get the value of name
  String get personName => name;

  walking() => print('$name is walking');

  talking() => print('$name is talking');
}

int main() {
  var firstPerson = Person("Sarah"."Female".25);
  print(firstPerson.personName);
}
Copy the code

Setters are functions that write properties of an object, using the set keyword:

class Person {
  String name;
  String gender;
  int age;

  String get personName => name;

	// The setter function sets the age value
  void set personAge(num val) {
    if (val < 0) {
      print("Age cannot be negative");
    } else {
      this.age = val;
    }
  }

  walking() => print('$name is walking');

  talking() => print('$name is talking');
}

int main() {
  var firstPerson = Person();
  firstPerson.personAge = - 5;
  print(firstPerson.age);
}
Copy the code

Lines 9 through 15 create a setter function that sets the age value. A conditional judgment has also been added to the function so that we cannot enter a negative age. In line 23, we set the age value for firstPerson using the personAge setter function.

withSetStore unique values

Lists are one of the most common collection types in Dart, but lists can hold duplicates. Sometimes we just want a Set of unique values, and that’s where Set comes in.


final countriesSet = {
  'USA'.'India'.'Iceland'.'USA'};Copy the code

Two elements cannot be the same in a Set, so the above code will have a warning and will not compile. Likewise, using const set will not compile.

6. Use the Inspect function

Inspect is often used in web development because it tells us all the attributes applied to HTML tags. Dart provides similar functionality, which we call Flutter Inspect. This feature greatly simplifies the development of a Flutter application to find any control on the screen and view the properties applied to it.

Inspect also helps us visualize the TREE of Flutter controls to understand the layout or determine layout problems.

To use it, follow these steps:

  • Click on theFlutter Inspector.
  • Click on theEnable select Widget mode.
  • Select the control on the screen for more information

7. Use Sync and Async generators

In Dart, a generator can generate a series of values. Dart has two generator functions:

  • Synchrogenerator: Returns an iterable object
  • Asynchronous generator:returnStreamobject

In other words, a synchro generator returns a collection of values that can be accessed sequentially. To do this, we mark the function body sync*. We’ll use the yield statement as the value.

可迭代<int> count(int n) sync* {
  for (var i = 1; i <= n; i++) {
    yieldi; }}Copy the code

The asynchronous generator returns a Stream object that makes it possible to receive a series of events. We can do this by marking the function body async*. We’ll use the yield statement as the value.

Stream<int> countStream(int n) async* {
  for (var i = 1; i <= n; i++) {
    yieldi; }}Copy the code

What will you study next?

We hope these tips help you take full advantage of Dart and all the features it offers. Flutter and Dart are a powerful set of tools for building applications that feel native and fluid. Other advanced Dart features to examine next are:

  • nestedifStatement propagation operator
  • Name the constructor and initializer list
  • The Dart library
  • Enumerated type

Happy study!

If you find any mistakes in your translation or other areas that need to be improved, you are welcome to the Nuggets Translation Program to revise and PR your translation, and you can also get the corresponding reward points. The permanent link to this article at the beginning of this article is the MarkDown link to this article on GitHub.


The Nuggets Translation Project is a community that translates quality Internet technical articles from English sharing articles on nuggets. The content covers Android, iOS, front-end, back-end, blockchain, products, design, artificial intelligence and other fields. If you want to see more high-quality translation, please continue to pay attention to the Translation plan of Digging Gold, the official Weibo, Zhihu column.