当前位置:网站首页>[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 )
边栏推荐
- CheckListBox control usage summary
- Research Report on the overall scale, major manufacturers, major regions, products and applications of capacitive voltage transformers in the global market in 2022
- NMF-matlab
- 分享几个图床网址,便于大家分享图片
- 自动化制作视频
- 【871. 最低加油次数】
- Why do I have a passion for process?
- 【Hot100】22. bracket-generating
- Burp install license key not recognized
- 【JS】获取hash模式下URL的搜索参数
猜你喜欢

How to do interface testing? After reading this article, it will be clear

【871. 最低加油次数】

B-end e-commerce - reverse order process
![[daily question] 241 Design priorities for operational expressions](/img/27/4ad1a557e308e4383335f51a51adb0.png)
[daily question] 241 Design priorities for operational expressions
[译]深入了解现代web浏览器(一)

励志!大凉山小伙全奖直博!论文致谢看哭网友

Use graalvm native image to quickly expose jar code as a native shared library

One side is volume, the other side is layoff. There are a lot of layoffs in byte commercialization department. What do you think of this wave?

Basic concept of database, installation and configuration of database, basic use of MySQL, operation of database in the project

Interested parties add me for private chat
随机推荐
Is it safe to buy funds on securities accounts? Where can I buy funds
Data preparation for behavior scorecard modeling
NMF-matlab
JDBC | Chapter 4: transaction commit and rollback
Cron expression (seven subexpressions)
Sometimes only one line of statements are queried, and the execution is slow
Complete example of pytorch model saving +does pytorch model saving only save trainable parameters? Yes (+ solution)
I would like to ask what securities dealers recommend? Is it safe to open a mobile account?
[NLP] a detailed generative text Abstract classic paper pointer generator
Google Earth engine (GEE) - Landsat 9 image full band image download (Beijing as an example)
sense of security
B端电商-订单逆向流程
Esp32c3 crash analysis
Use IDM to download Baidu online disk files (useful for personal testing) [easy to understand]
面试经验总结,为你的offer保驾护航,满满的知识点
【Hot100】22. bracket-generating
Jetson XAVIER NX上ResUnet-TensorRT8.2速度與顯存記錄錶(後續不斷補充)
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
ROS learning (10): ROS records multiple topic scripts
CRM客户关系管理系统