Dart & Flutter Easy Wins this article is a translation from Code With Andrea’s Dart & Flutter Easy Wins. It shares some tips on the Dart for Flutter language level. These tips help you write lean, efficient, Google-compliant code that will be updated from time to time.

language

const final var

Use as const as possible, and if not final, var last.

const text = 'I am a doctor.';
Copy the code

Using type declarations

Type declarations for generic types make code safer

const ciyies = <String> ['Lodon'.'Beijing'.15];
Copy the code

No parameter is used_The statement

MaterialPageRoute(Builder: (_) => DetailPage(),);Copy the code

usecollection-ifspreads

final restaurant = {
    'name': 'Pizza'.'cuisine': 'Italian'.if(addRatings) ... {'avaRatting': avgRatting,
        'numRattings': numRattings,
    }
}
Copy the code

use.Multiple consecutive calls to a variable

finalpath = Path() .. moveTo(0.0)
  ..moveTo(1.0)
  ..moveTo(0.1)
Copy the code

usecatch onCatch different types of errors

try {
	await authScerice.signInAnonymously();
} on PlatformException catch (e) {
  // handle PlatformException
} on SocketException catch (e) {
	// handle SocketException
} catch (e) {
	// handle everything
}
Copy the code

rewritetoStringImprove debug Experience

class Point { 
  const Point(this.x, this.y);
	final num x;
	final num y;
  @override
  String toString() => '($x.$y) ';
}

print(Point(1.2));
Copy the code

use??Returns anull

final value = list[4]????0;
Copy the code

use"" "Enter multiple lines of text

print("""
This is a short sentence.
This is an other short sentence.
""");
Copy the code

use.Quickly implement shallow copy of list

const list = [1.2.3];
final copy = [...list];
Copy the code

use?Avoid calling methods on NULL

someClass? .call();Copy the code

By implementingcallMethod that allows classes to be called like methods

class PasswordValidator {
	bool call(String password) {
		return password.length > 10; }}void main() {
	final validator = PasswordValidator();
	validator('test'); // false
	validator('test1234'); // false validator('not-so-frozen-arctic'); // true
}
Copy the code

useFuture.waitExecute multiple asynchronous methods simultaneously

class CovidAPI {
	Future<int> getCases() => Future.value(1000);
	Future<int> getRecovered()
	Future.value(100);
	Future<int> getDeaths() => Future.value(10);
}
void main() async {
	final api = CovidAPI();
	final values = await Future.wait([
		api.getCases(),
		api.getRecovered(),
		api.getDeaths()
	1]);
	print(values); / / [1000, 100, 10]
}
Copy the code

useshow hideHide parts of the API that import packages

// shows Stream only
import 'dart :async' show Stream;
// shows all but StreamController
import 'dart :async' hide StreamController;
Copy the code

useasResolve package naming conflicts

import 'package:http/http.dart' as http;
Copy the code

usetoStringAsFixedFormatting a float

const x= 12.34567;
print(x.toString());
/ / 12.34567
print(x.toStringAsFixed(3));
// 12.346 (3 decimal digits)
Copy the code

StringIntCan multiply

for (var i= 1; i <= 5; i++) {
	print('😄' * i);
}
// Output:
😄
😄😄
😄😄😄
😄😄😄😄
😄😄😄😄😄
Copy the code

Using named constructors, create multiple constructors

class Complex {
  final double re;
  final double im;
  Complex(this.re, this.im);
  
  Complex.real(this.re): im = 0;
}
Copy the code

Use factory constructors instead of static methods

The difference between a “factory constructor” and a “static method”

class Item {
	final String itemId;
	final double price;
	item({required this.itemId, required this.price});
	factory Item.fromJson(Map<String.dynamic> json) { 
    	return Item(
			itemId: json['itemId'] as String,
			price: json['price'] as double,); }static Item fromMap(Map-String.dynamic> json) { 
    	return Item(
			itemId: json['itemId'] as String,
			price: json['price'] as double,); }}Copy the code

The singleton

class Singleton {
  Singleton._();
  static final instance = Singleton._();
}
Copy the code

Consider usingset

final citiesSet = {'London'.'Beijin'.'Rome'};
Copy the code

Safely traverse the map

for (final entry in activeties.entries) {
  print('${entry.key}:${entry.value}');
}
Copy the code

Import different files depending on platform

// stub implementation
import 'copy_to_clipboard_stub.dart'
// dart:html implementation
if (dart.library.html) 'copy_to_clipboard_web.dart'
// dart:io implementation
if (dart.library.io) 'copy_to_clipboard_non_web. dart';
Copy the code

get setmethods

double celsius;
double get farenheit => celsius * 1.8 + 32;
set farenheit(double degrees) => celsius = (degrees- 32) / 1.8;
Copy the code

Delay the

await Future.delayed(Duration(seconds: 2));
	// Return mock result return 100;
}
Copy the code

assertinterrupt

assert(url.startsWith('https'))
Copy the code

useNeverConstruct a function that does not return

// this function can never return, only throw
Never wrongType(String type, Object value) {
	throw ArgumentError('Expected $type, but was ${value.runtimeType}. ');
}
Copy the code

package

equatable

Quick implementation of hashCode == toString

import 'package:equatable/equatable.dart';
class Person extends Equatable { 
  final String name;
	Person(this.name);
  
	@override
	List<object> get props => [name];
  
	@override
	bool get stringify => true;
}
Copy the code

dartx

Use date and time more elegantly

print(5.seconds); / / 0:00:05. 000000
print(2.minutes); / / 0:02:00. 000000
print(1.hours.inSeconds); / / 3600
Copy the code

logger

Enhanced log