当前位置:网站首页>[fluent] dart generic (generic class | generic method | generic with specific type constraints)
[fluent] dart generic (generic class | generic method | generic with specific type constraints)
2022-07-02 20:30:00 【Programmer community】
List of articles
- One 、Dart Generic classes and generic methods
- Two 、Dart Specific type constraints in generics
- 3、 ... and 、Dart Built in generics
- Four 、 Complete code example
- 5、 ... and 、 Related resources
One 、Dart Generic classes and generic methods
Generic action : by class , Interface , Method Provide reusability , Support data types with uncertain types ;
Generic classes : Improve code reuse ;
Generic methods : Parameters or return values have generic type constraints , The parameter or return value type must conform to the corresponding generic type , When using generic types, type checking constraints will be carried out , If the wrong type is set , Compile times error ;
Generic class examples :
/// Generic action : by class , Interface , Method Provide reusability , Support data types with uncertain types ////// Generic classes : Improve code reuse /// This class is a cache class , The data type of cache is T Generic , This type can be any type class Cache<T>{
/// Cache data is stored in this Map Collection Map<String, Object> _map = Map(); /// Set generic cache data , The method is generic /// Here will be T Type of data is stored in map Collection void setCacheItem(String key, T value){
_map[key] = value; } /// Fetch generic cache data , The method is generic T getCachedItem(String key){
return _map[key]; }}
Test the above generic classes :
/// Generic test class class Generic{
/// This method tests generic classes and generic methods void test(){
// Create generic class objects , The generic type is set to String type Cache<String> cache = Cache(); // When calling generic methods , The passed in parameter must conform to the corresponding generic type // Generic constraint : When using generic types, type checking constraints will be carried out , If the wrong type is set , Compile times error cache.setCacheItem("name", "Tom"); // Get cached content String value = cache.getCachedItem("name"); print(" Generic testing , Type string , The obtained cache content is ${value}"); // Create generic class objects , The generic type is set to int type Cache<int> cache2 = Cache(); // When calling generic methods , The passed in parameter must conform to the corresponding generic type // Generic constraint : When using generic types, type checking constraints will be carried out , If the wrong type is set , Compile times error cache2.setCacheItem("age", 18); // Get cached content int value2 = cache2.getCachedItem("age"); print(" Generic testing , Type integer , The obtained cache content is ${value2}"); }}
Print the results :
I/flutter (24673): Generic testing , Type string , The obtained cache content is TomI/flutter (24673): Generic testing , Type integer , The obtained cache content is 18
Two 、Dart Specific type constraints in generics
Generics can also have specific type constraints , If you specify that the generic type must be a subclass of a class , Use <T extends Person> Constraining that the generic must be a subclass of a class ;
Generic class sample code :
/// Specific type constraints in generics /// Constrain generics to subclasses of a type class Member<T extends Person>{
T _person; /// Set... In the constructor T _person Members of the value of the Member(this._person); /// obtain _person Name String getName(){
return _person.name; }}
The two classes mentioned above are in 【Flutter】Dart object-oriented ( Name the construction method | Factory construction method | Name factory construction method ) In the definition of ;
Test the above generic classes :
/// Generic class testing /// Class generic requirements are T extends Person , The generic type must be Person Subclasses of /// Student yes Person Subclasses of Member<Student> member = Member(Student(6, "Tom", 18)); String name = member.getName(); print(" Generic class testing , Acquired T extends Person generic name Field is ${name}");
Test print results :
I/flutter (24673): Generic class testing , Acquired T extends Person generic name Field is Tom
3、 ... and 、Dart Built in generics
stay Flutter Of main.dart Medium State It's a generic class ;
class _MyHomePageState extends State<MyHomePage> {
}
State Class requires a generic T , This generic type must inherit StatefulWidget class ;
abstract class State<T extends StatefulWidget> extends Diagnosticable {
}
Here MyHomePage Namely The generic type , yes StatefulWidget Subclasses of classes , accord with Generic requirements ;
Four 、 Complete code example
Generic classes , Generic methods , Generic test related code :
import 'package:flutterapphello/Dart_OOP.dart';/// Generic test class class Generic{
/// This method tests generic classes and generic methods void test(){
// Create generic class objects , The generic type is set to String type Cache<String> cache = Cache(); // When calling generic methods , The passed in parameter must conform to the corresponding generic type // Generic constraint : When using generic types, type checking constraints will be carried out , If the wrong type is set , Compile times error cache.setCacheItem("name", "Tom"); // Get cached content String value = cache.getCachedItem("name"); print(" Generic testing , Type string , The obtained cache content is ${value}"); // Create generic class objects , The generic type is set to int type Cache<int> cache2 = Cache(); // When calling generic methods , The passed in parameter must conform to the corresponding generic type // Generic constraint : When using generic types, type checking constraints will be carried out , If the wrong type is set , Compile times error cache2.setCacheItem("age", 18); // Get cached content int value2 = cache2.getCachedItem("age"); print(" Generic testing , Type integer , The obtained cache content is ${value2}"); /// Generic class testing /// Class generic requirements are T extends Person , The generic type must be Person Subclasses of /// Student yes Person Subclasses of Member<Student> member = Member(Student(6, "Tom", 18)); String name = member.getName(); print(" Generic class testing , Acquired T extends Person generic name Field is ${name}"); }}/// Generic action : by class , Interface , Method Provide reusability , Support data types with uncertain types ////// Generic classes : Improve code reuse /// This class is a cache class , The data type of cache is T Generic , This type can be any type class Cache<T>{
/// Cache data is stored in this Map Collection Map<String, Object> _map = Map(); /// Set generic cache data , The method is generic /// Here will be T Type of data is stored in map Collection void setCacheItem(String key, T value){
_map[key] = value; } /// Fetch generic cache data , The method is generic T getCachedItem(String key){
return _map[key]; }}/// Specific type constraints in generics /// Constrain generics to subclasses of a type class Member<T extends Person>{
T _person; /// Set... In the constructor T _person Members of the value of the Member(this._person); /// obtain _person Name String getName(){
return _person.name; }}
It involves Person and Student class :
/// Definition Dart class /// And Java Language is similar to , All classes inherit by default Object class class Person{
/// Defining variables String name; int age; /// Private field int _achievement; /// Standard construction method , The following method is a common construction method Person(this.name, this.age); /// get Method : Set private fields achievement Of get Method , /// Let the outside world have access to Person Object's _achievement Private member int get achievement => _achievement; /// set Method : Set private fields achievement Of set Method , /// Let the outside world set Person Object's _achievement Private member value set achievement(int achievement){
_achievement = achievement; } /// Static methods , Called by the class name static log(){
print("log"); } /// Overrides the method of the parent class @override String toString() {
return "$name : $age"; }}/// Inherit class Student extends Person{
/// Private variables , Variables starting with an underscore are private variables int _grade; String school; String city; String address; /// Parent constructor call : If the parent class has a constructor with non empty parameters , Subclasses must implement constructors with the same parameters /// If the class has a parent , Then call the constructor of the parent class first , Complete the initialization of the parent class /// Then you can complete your initialization /// /// this.school Specify own parameters /// {this.school} Is an optional parameter , The optional parameter must be the last in the constructor parameter list /// /// Default parameters : Among the optional parameters, if the user does not initialize the optional parameter , Then specify a default value /// {this.city = " Beijing "} Specifies if the user does not initialize city Variable , Then initialize it " Beijing " A string value /// /// Initialization list : The content after the colon is the initialization list /// The parent constructor is also an initialization list /// In addition to the parent class constructor , You can also initialize sample variables before subclass constructor body /// Different initialization instance variables are separated by commas /// /// Parent class constructor : If the parent class has no default constructor ( Nonparametric construction method ) , /// The parent constructor must be called in the initialization list , super(name, age) ; /// /// Construct method body : It can be omitted ; Student(this._grade, String name, int age, {
this.school, this.city = " Beijing "}) : address = " Haidian District, Beijing " , super(name, age); // Name the construction method // Define format : Class name . Method name () // Parent constructor : If the parent class does not have a default constructor , The subclass must call the constructor of the parent class Student.cover(Student student):super(student.name, student.age); // A named constructor can also have a method body Student.init(Student student):super(student.name, student.age){
print(" Name the construction method : name : ${student.name}, age : ${student.age}"); } // Name factory construction method : factory Class name . Method name // The named factory constructor can have a return value // If there is final Decorated member , It must be initialized in the named constructor // But in the naming factory construction method , It can be uninitialized final Type members // The named factory constructor can have a return value factory Student.init2(){
return Student(1, "Tom", 18); }}
Test code entry : stay main.dart Medium _MyHomePageState Class build In the method ;
/// Omit other source code class _MyHomePageState extends State<MyHomePage> {
@override Widget build(BuildContext context) {
// Test generics Generic generic = Generic(); generic.test(); }}
Print the results :
I/flutter (24673): Generic testing , Type string , The obtained cache content is TomI/flutter (24673): Generic testing , Type integer , The obtained cache content is 18I/flutter (24673): Generic class testing , Acquired T extends Person generic name Field is Tom
5、 ... and 、 Related resources
Reference material :
- Flutter Official website : https://flutter.dev/
- Flutter Developing documents : https://flutter.cn/docs ( Strongly recommend )
- official GitHub Address : https://github.com/flutter
- Flutter The Chinese community : https://flutter.cn/
- Flutter Practical tutorial : https://flutter.cn/docs/cookbook
- Flutter CodeLab : https://codelabs.flutter-io.cn/
- Dart Chinese document : https://dart.cn/
- Dart Developer website : https://api.dart.dev/
- Flutter Chinese net ( unofficial , The translation is very good ) : https://flutterchina.club/ , http://flutter.axuer.com/docs/
- Flutter Related issues : https://flutterchina.club/faq/ ( It is recommended to watch it at the introductory stage )
Blog source download :
GitHub Address : https://github.com/han1202012/flutter_app_hello ( Keep updating with the progress of the blog , There may not be the source code of this blog )
Blog source snapshot : https://download.csdn.net/download/han1202012/15463304( The source code snapshot of this blog , You can find the source code of this blog )
边栏推荐
- Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)
- esp32c3 crash分析
- [daily question] 241 Design priorities for operational expressions
- API documentation tool knife4j usage details
- AMD's largest transaction ever, the successful acquisition of Xilinx with us $35billion
- 想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
- 现在券商的优惠开户政策什么?实际上网上开户安全么?
- [cloud native topic -49]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - basic processes and steps
- JS how to get integer
- Cs5268 perfectly replaces ag9321mcq typec multi in one docking station solution
猜你喜欢
【871. 最低加油次数】
[NLP] a detailed generative text Abstract classic paper pointer generator
The metamask method is used to obtain account information
Implementation of online shopping mall system based on SSM
疫情封控65天,我的居家办公心得分享 | 社区征文
B端电商-订单逆向流程
Activation function - relu vs sigmoid
Second hand housing data analysis and prediction system
Overview of browser caching mechanism
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
随机推荐
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
勵志!大凉山小夥全獎直博!論文致謝看哭網友
Start practicing calligraphy
The metamask method is used to obtain account information
[译]深入了解现代web浏览器(一)
Data preparation for behavior scorecard modeling
Function, function, efficiency, function, utility, efficacy
Jetson XAVIER NX上ResUnet-TensorRT8.2速度與顯存記錄錶(後續不斷補充)
有时候只查询一行语句,执行也慢
八年测开经验,面试28K公司后,吐血整理出高频面试题和答案
Want to ask, is there any discount for opening an account now? Is it safe to open an account online?
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
【Kubernetes系列】kubeadm reset初始化前后空间、内存使用情况对比
Development skills of rxjs observable custom operator
【JS】获取hash模式下URL的搜索参数
什么叫在线开户?现在网上开户安全么?
想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
Postman接口测试实战,这5个问题你一定要知道
Esp32c3 crash analysis
CRM客户关系管理系统