当前位置:网站首页>[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 )
边栏推荐
- 【NLP】一文详解生成式文本摘要经典论文Pointer-Generator
- 【Kubernetes系列】kubeadm reset初始化前后空间、内存使用情况对比
- [871. Minimum refueling times]
- NMF-matlab
- Notes on hardware design of kt148a voice chip IC
- 为什么我对流程情有独钟?
- [cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process
- [译]深入了解现代web浏览器(一)
- Cron expression (seven subexpressions)
- CheckListBox control usage summary
猜你喜欢
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
[real case] trap of program design - beware of large data
Resunnet - tensorrt8.2 Speed and Display record Sheet on Jetson Xavier NX (continuously supplemented)
burp 安装 license key not recognized
Outsourcing for three years, abandoned
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
【每日一题】241. 为运算表达式设计优先级
SBT tutorial
Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
勵志!大凉山小夥全獎直博!論文致謝看哭網友
随机推荐
Workplace four quadrant rule: time management four quadrant and workplace communication four quadrant "suggestions collection"
JDBC | Chapter 4: transaction commit and rollback
Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)
通信人的经典语录,第一条就扎心了……
Overview of browser caching mechanism
Research Report on the overall scale, major manufacturers, major regions, products and applications of capacitive voltage transformers in the global market in 2022
[Chongqing Guangdong education] reference materials for labor education of college students in Nanjing University
Cron表达式(七子表达式)
AcWing 340. Solution to communication line problem (binary + double ended queue BFS for the shortest circuit)
有时候只查询一行语句,执行也慢
Function, function, efficiency, function, utility, efficacy
勵志!大凉山小夥全獎直博!論文致謝看哭網友
【Hot100】23. Merge K ascending linked lists
Postman interface test practice, these five questions you must know
【Hot100】21. Merge two ordered linked lists
测试人员如何做不漏测?这7点就够了
[JS] get the search parameters of URL in hash mode
【QT】QPushButton创建
Attack and defense world PWN question: Echo
Sometimes only one line of statements are queried, and the execution is slow