当前位置:网站首页>[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 )
边栏推荐
- Conscience summary! Jupyter notebook from Xiaobai to master, the nanny tutorial is coming!
- for(auto a : b)和for(auto &a : b)用法
- AcWing 341. Optimal trade solution (shortest path, DP)
- 在券商账户上买基金安全吗?哪里可以买基金
- 【Hot100】21. 合并两个有序链表
- B端电商-订单逆向流程
- Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)
- 功能、作用、效能、功用、效用、功效
- 勵志!大凉山小夥全獎直博!論文致謝看哭網友
- 想问问,现在开户有优惠吗?在线开户是安全么?
猜你喜欢
![[internship] solve the problem of too long request parameters](/img/42/413cf867f0cb34eeaf999f654bf02f.png)
[internship] solve the problem of too long request parameters

How to realize the function of detecting browser type in Web System

【NLP】一文详解生成式文本摘要经典论文Pointer-Generator

Implementation of online shopping mall system based on SSM

SBT tutorial

CS5268完美代替AG9321MCQ Typec多合一扩展坞方案

Review of the latest 2022 research on "deep learning methods for industrial defect detection"

burp 安装 license key not recognized

Driverless learning (4): Bayesian filtering

Jetson XAVIER NX上ResUnet-TensorRT8.2速度与显存记录表(后续不断补充)
随机推荐
Database schema notes - how to choose the right database in development + who invented relational database?
Want to ask, is there any discount for opening an account now? Is it safe to open an account online?
Driverless learning (III): Kalman filter
[fluent] dart function (function composition | private function | anonymous function | function summary)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of shock absorber oil in the global market in 2022
Design and implementation of ks004 based on SSH address book system
Automatic reading of simple books
CheckListBox control usage summary
Spark source code compilation, cluster deployment and SBT development environment integration in idea
Automated video production
[cloud native topic -49]:kubesphere cloud Governance - operation - step by step deployment of microservice based business applications - basic processes and steps
[kubernetes series] comparison of space and memory usage before and after kubedm reset initialization
sql-labs
I did a craniotomy experiment: talk about macromolecule coding theory and Lao Wang's fallacy from corpus callosum and frontal leukotomy
Resunnet - tensorrt8.2 Speed and Display record Sheet on Jetson Xavier NX (continuously supplemented)
Research Report on the overall scale, major manufacturers, major regions, products and application segmentation of the inverted front fork of the global market in 2022
Research Report on the overall scale, major manufacturers, major regions, products and applications of metal oxide arresters in the global market in 2022
After eight years of test experience and interview with 28K company, hematemesis sorted out high-frequency interview questions and answers
Notes on hardware design of kt148a voice chip IC
【实习】解决请求参数过长问题