当前位置:网站首页>[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 18Two 、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 Tom3、 ... 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 Tom5、 ... 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 )
边栏推荐
- GCC: Graph Contrastive Coding for Graph Neural NetworkPre-Training
- Summary of interview experience, escort your offer, full of knowledge points
- Conscience summary! Jupyter notebook from Xiaobai to master, the nanny tutorial is coming!
- Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of voltage source converters in the global market in 2022
- CRM Customer Relationship Management System
- 【每日一题】241. 为运算表达式设计优先级
- Taiwan SSS Xinchuang sss1700 replaces cmmedia cm6533 24bit 96KHz USB audio codec chip
- 笔记本安装TIA博途V17后出现蓝屏的解决办法
- Self-Improvement! Daliangshan boys all award Zhibo! Thank you for your paper
- JDBC | Chapter 3: SQL precompile and anti injection crud operation
猜你喜欢

【Hot100】21. 合并两个有序链表

Shardingsphere jdbc5.1.2 about select last_ INSERT_ ID () I found that there was still a routing problem

Friends who firmly believe that human memory is stored in macromolecular substances, please take a look

Implementation of online shopping mall system based on SSM

Solution to blue screen after installing TIA botu V17 in notebook

After eight years of test experience and interview with 28K company, hematemesis sorted out high-frequency interview questions and answers

After 65 days of closure and control of the epidemic, my home office experience sharing | community essay solicitation

Detailed upgrade process of AWS eks

SBT tutorial

API documentation tool knife4j usage details
随机推荐
Workplace four quadrant rule: time management four quadrant and workplace communication four quadrant "suggestions collection"
[cloud native topic -50]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - database middleware MySQL microservice deployment process
Resunnet - tensorrt8.2 Speed and Display record Sheet on Jetson Xavier NX (continuously supplemented)
After 65 days of closure and control of the epidemic, my home office experience sharing | community essay solicitation
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of voltage source converters in the global market in 2022
B-end e-commerce - reverse order process
API文档工具knife4j使用详解
想请教一下,究竟有哪些劵商推荐?手机开户是安全么?
JDBC | Chapter 3: SQL precompile and anti injection crud operation
Codeforces round 651 (Div. 2) (a thinking, B thinking, C game, D dichotomy, e thinking)
Burp install license key not recognized
[NLP] a detailed generative text Abstract classic paper pointer generator
Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)
【Hot100】22. 括号生成
For (Auto A: b) and for (Auto & A: b) usage
I would like to ask what securities dealers recommend? Is it safe to open a mobile account?
burp 安装 license key not recognized
Is it safe to buy funds on securities accounts? Where can I buy funds
Research Report on the overall scale, major manufacturers, major regions, products and applications of outdoor vacuum circuit breakers in the global market in 2022
Sometimes only one line of statements are queried, and the execution is slow