current position:Home>Eight skills of dart development
Eight skills of dart development
2021-08-27 07:48:57 【Breeze_ Luckly】
This is my participation 8 The fourth of the yuegengwen challenge 20 God , Check out the activity details :8 Yuegengwen challenge . For the Nuggets August is more challenging
, Specially bring you what I summarized in the development dart Related skills , This is a # dart Developed 7 Tips The second season of
8. Use named constructors and initialization lists to get more ergonomic API.
Suppose you want to declare a class that represents a temperature value .
You can make your class API Explicitly support Two Two named constructors, Celsius and Fahrenheit :
class Temperature {
Temperature.celsius(this.celsius);
Temperature.fahrenheit(double fahrenheit)
: celsius = (fahrenheit - 32) / 1.8;
double celsius;
}
Copy code
This class only needs one Storage Variable to represent temperature , And use the initialization list to convert Fahrenheit temperature to Celsius temperature .
This means that you can declare the temperature value like this :
final temp1 = Temperature.celsius(30);
final temp2 = Temperature.fahrenheit(90);
Copy code
9. getter and setter
stay Temperature
In the class above ,celsius
Declared as a storage variable .
But users may prefer to be in Fahrenheit obtain or Set up temperature .
This can be used getter and setter Easy to finish , They allow you to define calculated variables . This is an updated course :
class Temperature {
Temperature.celsius(this.celsius);
Temperature.fahrenheit(double fahrenheit)
: celsius = (fahrenheit - 32) / 1.8;
double celsius;
double get fahrenheit
=> celsius * 1.8 + 32;
set fahrenheit(double fahrenheit)
=> celsius = (fahrenheit - 32) / 1.8;
}
Copy code
This makes it easy to get or set the temperature using degrees Fahrenheit or Celsius :
final temp1 = Temperature.celsius(30);
print(temp1.fahrenheit);
final temp2 = Temperature.fahrenheit(90);
temp2.celsius = 28;
Copy code
The bottom line : Use a named constructor 、getter and setter To improve the design of classes .
10. Use underscores on unused function arguments
stay Flutter in , We often use widgets with function parameters . A common example is ListView.builder
:
class MyListView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemBuilder: (context, index) => ListTile(
title: Text('all the same'),
),
itemCount: 10,
);
}
}
Copy code
under these circumstances , We don't use (context, index)
Parameters of itemBuilder
. So we can replace them with underscores :
ListView.builder(
itemBuilder: (_, __) => ListTile(
title: Text('all the same'),
),
itemCount: 10,
)
Copy code
Be careful : These two parameters are different (_
and __
), Because they are Individual identifiers .
11. Need a class that can only be instantiated once ( Another example )? Use static instance variables with private constructors .
The most important feature of a singleton is that there can only be One its example . This is useful for modeling file systems and so on .
// file_system.dart
class FileSystem {
FileSystem._();
static final instance = FileSystem._();
}
Copy code
To be in Dart Create a singleton in , You can declare a named constructor and use _
The syntax makes it private .
then , You can use it to create a static final instance of the class .
therefore , Any code in other files can only pass through instance
Variable to access this class :
// some_other_file.dart
final fs = FileSystem.instance;
// do something with fs
Copy code
Be careful : If you are not careful ,final May cause many problems . Before using them , Make sure you understand their shortcomings .
12. Need to collect unique set? Use collections instead of lists .
Dart The most commonly used collection type in is List
.
But the list can have duplicate items , Sometimes it's not what we want :
const citiesList = [
'London',
'Paris',
'Rome',
'London',
];
Copy code
We can Set
Use... When you need a unique set of values a ( Please note that Use final
):
// set is final, compiles
final citiesSet = {
'London',
'Paris',
'Rome',
'London', // Two elements in a set literal shouldn't be equal
};
Copy code
The above code generates a warning , because London
Included twice . If we try to be right const
set Do the same thing , Will receive an error and our code will not compile :
// set is const, doesn't compile
const citiesSet = {
'London',
'Paris',
'Rome',
'London', // Two elements in a constant set literal can't be equal
};
Copy code
When we work with Taiwan , We can get useful API, Such as union
,difference
and intersection
:
citiesSet.union({'Delhi', 'Moscow'});
citiesSet.difference({'London', 'Madrid'});
citiesSet.intersection({'London', 'Berlin'});
Copy code
The bottom line : When you create a collection , Ask yourself if you want its project to be unique , And consider using a collection .
13. How to use try、on、catch、rethrow、finally
try
also catch
In use based on Future Of API Very ideal , If something goes wrong , these API Could throw an exception .
This is a complete example , Shows how to make the most of them :
Future<void> printWeather() async {
try {
final api = WeatherApiClient();
final weather = await api.getWeather('London');
print(weather);
} on SocketException catch (_) {
print('Could not fetch data. Check your connection.');
} on WeatherApiException catch (e) {
print(e.message);
} catch (e, st) {
print('Error: $e\nStack trace: $st');
rethrow;
} finally {
print('Done');
}
}
Copy code
Some precautions :
- You can add multiple
on
Clause to handle different types of exceptions . - You can use fallback
catch
Clause to handle all exceptions that do not match any of the above types . - You can use
rethrow
Statement throws the current exception up the call stack , Keep stack trace at the same time . - You can use
finally
stayFuture
Run some code when you're done , Whether it succeeds or fails .
If you are using or designing something based on Future Of API, Be sure to handle exceptions as needed .
14. common Future Constructors
DartFuture
Class with some convenient factory constructors :Future.delayed
,Future.value
and Future.error
.
We can Future.delayed
Used to create a Future
Waiting for a certain delay . The second parameter is a ( Optional ) Anonymous functions , You can use it to complete a value or throw an error :
await Future.delayed(Duration(seconds: 2), () => 'Latte');
Copy code
But sometimes we want to create a Future
Immediate :
await Future.value('Cappuccino');
await Future.error(Exception('Out of milk'));
Copy code
We can use Future.value
A value to successfully complete , perhaps Future.error
Complete with an error .
You can use these constructors to emulate data from Future Of API Response . This is useful when writing mock classes in your test code .
15. Universal flow constructor
Stream Class also comes with some convenient constructors . Here are the most common :
Stream.fromIterable([1, 2, 3]);
Stream.value(10);
Stream.empty();
Stream.error(Exception('something went wrong'));
Stream.fromFuture(Future.delayed(Duration(seconds: 1), () => 42));
Stream.periodic(Duration(seconds: 1), (index) => index);
Copy code
- Used to select from the list of values
Stream.fromIterable
Create aStream
. - Use
Stream.value
, If you have only one value . - be used for
Stream.empty
Create an empty stream . - be used for
Stream.error
Create a stream with error values . - be used for
Stream.fromFuture
Create a stream that contains only one value , This value will be available at future completion . - be used for
Stream.periodic
Create a periodic flow of events . You can use a AppointDuration
Is the time interval between events , And specify an anonymous function to generate each value given its index in the stream .
16. Synchronous and asynchronous generators
stay Dart in , We can Sync The generator is defined as a return Function of Iterable
:
Iterable<int> count(int n) sync* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Copy code
This use sync*
grammar . Inside the function , We can “ Generate ” or yield
Multiple values . These will Iterable
Returns... When the function is complete .
On the other hand , asynchronous The generator is a return a Function of Stream
:
Stream<int> countStream(int n) async* {
for (var i = 1; i <= n; i++) {
yield i;
}
}
Copy code
This uses this async*
grammar . Inside the function , We can yield
Take the same value as in the case of synchronization .
But if we want to , We can use await
be based on Future Of API, Because this is a asynchronous generator :
Stream<int> countStream(int n) async* {
for (var i = 1; i <= n; i++) {
// dummy delay - this could be a network request
await Future.delayed(Duration(seconds: 1));
yield i;
}
}
Copy code
copyright notice
author[Breeze_ Luckly],Please bring the original link to reprint, thank you.
https://en.qdmana.com/2021/08/20210827074852050e.html
The sidebar is recommended
- Crazy blessing! Tencent boss's "million JVM learning notes", real topic of Huawei Java interview 2020-2021
- JS JavaScript how to get the subscript of a value in the array
- How to implement injection in vuex source code?
- JQuery operation select (value, setting, selected)
- One line of code teaches you how to advertise on Tanabata Valentine's Day - Animation 3D photo album (music + text) HTML + CSS + JavaScript
- An article disassembles the pyramid architecture behind the gamefi outbreak
- BEM - a front-end CSS naming methodology
- [vue3] encapsulate custom global plug-ins
- Error using swiper plug-in in Vue
- Another ruthless character fell by 40000, which was "more beautiful" than Passat and maiteng, and didn't lose BMW
guess what you like
-
Huang Lei basks in Zhang Yixing's album, and the relationship between teachers and apprentices is no less than that in the past. Netizens envy Huang Lei
-
He was cheated by Wang Xiaofei and Li Chengxuan successively. Is an Yixuan a blessed daughter and not a blessed home?
-
Zhou Shen sang the theme song of the film "summer friends and sunny days" in mainland China. Netizen: endless aftertaste
-
Pink is Wangyuan online! Back to the peak! The new hairstyle is creamy and sassy
-
Front end interview daily 3 + 1 - day 858
-
Spring Webflux tutorial: how to build reactive web applications
-
[golang] walk into go language lesson 24 TCP high-level operation
-
August 23, 2021 Daily: less than three years after its establishment, Google dissolved the health department
-
The female doctor of Southeast University is no less beautiful than the female star. She has been married four times, and her personal experience has been controversial
-
There are many potential safety hazards in Chinese restaurant. The top of the program recording shed collapses, and the artist will fall down if he is careless
Random recommended
- Anti Mafia storm: He Yun's helpless son, Sun Xing, is destined to be caught by his dry son
- Introduction to flex flexible layout in CSS -- learning notes
- CSS learning notes - Flex layout (Ruan Yifeng tutorial summary)
- Today, let's talk about the arrow function of ES6
- Some thoughts on small program development
- Talk about mobile terminal adaptation
- Unwilling to cooperate with Wang Yibo again, Zhao Liying's fans went on a collective strike and made a public apology in less than a day
- JS function scope, closure, let, const
- Zheng Shuang's 30th birthday is deserted. Chen Jia has been sending blessings for ten years. Is it really just forgetting to make friends?
- Unveil the mystery of ascension
- Asynchronous solution async await
- Analysis and expansion of Vue infinite scroll source code
- Compression webpack plugin first screen loading optimization
- Specific usage of vue3 video play plug-in
- "The story of huiyeji" -- people are always greedy, and fairies should be spotless!
- Installing Vue devtool for chrome and Firefox
- Basic usage of JS object
- 1. JavaScript variable promotion mechanism
- Two easy-to-use animation JS that make the page move
- Front end Engineering - scaffold
- Java SQL Server intelligent fixed asset management, back end + front end + mobile end
- Mediator pattern of JavaScript Design Pattern
- Array de duplication problem solution - Nan recognition problem
- New choice for app development: building mobile applications using Vue native
- New gs8 Chengdu auto show announces interior Toyota technology blessing
- Vieira officially terminated his contract and left the team. The national security club sent blessings to him
- Less than 200000 to buy a Ford RV? 2.0T gasoline / diesel power, horizontal bed / longitudinal bed layout can be selected
- How does "heart 4" come to an end? Pinhole was boycotted by the brand, Ma Dong deleted the bad comments, and no one blessed him
- We are fearless in epidemic prevention and control -- pay tribute to the front-line workers of epidemic prevention!
- Front end, netty framework tutorial
- Xiaomi 11 | miui12.5 | android11 solves the problem that the httpcanary certificate cannot be installed
- The wireless charging of SAIC Roewe rx5 plus is so easy to use!
- Upload and preview pictures with JavaScript, and summarize the most complete mybatis core configuration file
- [25] typescript
- CSS transform Complete Guide (Second Edition) flight.archives 007
- Ajax foundation - HTTP foundation of interview essential knowledge
- Cloud lesson | explain in detail how Huawei cloud exclusive load balancing charges
- Decorator pattern of JavaScript Design Pattern
- [JS] 10. Closure application (loop processing)
- Left hand IRR, right hand NPV, master the password of getting rich