https://www.bilibili.com/video/BV1Kt42157Xv/
原文 https://ducafecat.com/blog/dart-syntax-record-usage-guide
学习如何使用Dart中的record类型,这种匿名、不可变的聚合类型将帮助您更高效地管理数据。
了解如何定义和使用,以及常见使用场景。
https://dart.dev/language/records
var name = 'Bob'; var age = 20; var isVip = true; var userInfo = (name, age, isVip); print('name: ${userInfo.$1}'); print('age: ${userInfo.$2}'); print('isVip: ${userInfo.$3}');
需要通过 userInfo.$1
的方式访问
var name = 'Bob'; var age = 20; var isVip = true; var userInfo = (name: name, age: age, isVip: isVip); print('name: ${userInfo.name}'); print('age: ${userInfo.age}'); print('isVip: ${userInfo.isVip}');
通过 name: name
方式指定名称,方便调用 userInfo.name
(String, int, bool) userInfo = (name, age, isVip); print('name: ${userInfo.$1}'); print('age: ${userInfo.$2}'); print('isVip: ${userInfo.$3}');
({String name, int age, bool isVip}) userInfo = (name: name, age: age, isVip: isVip); print('name: ${userInfo.name}'); print('age: ${userInfo.age}'); print('isVip: ${userInfo.isVip}');
// 定义 ({String name, int age, bool isVip}) userInfo; // 赋值 userInfo = (name: name, age: age, isVip: isVip);
// 定义,赋值 ({String name, int age, bool isVip}) userInfo = (name: name, age: age, isVip: isVip); // 解构读取 final (:name, :age, :isVip) = userInfo(json); print("$name, $age, $isVip");
({double latitude, double longitude}) getLocation() { // 返回经纬度 return (latitude: 37.7749, longitude: -122.4194); } void main(List<String> arguments) { var location = getLocation(); print( "Location latitude: ${location.latitude}, longitude: ${location.longitude}"); }
// 函数 (String name, int age) userInfo(Map<String, dynamic> json) { return (json['name'] as String, json['age'] as int); } // 数据 final json = <String, dynamic>{ 'name': 'Dash', 'age': 10, 'color': 'blue', }; // 执行处理 var (name, age) = userInfo(json); /* Equivalent to: var info = userInfo(json); var name = info.$1; var age = info.$2; */
如返回博客文章,我们需要一次返回文章、评论、关联推荐.
以前原来我们需要定义一个返回类 Class。
class ArticleDetail { final String article; final List<String> comments; final List<String> related; ArticleDetail(this.article, this.comments, this.related); }
Future<ArticleDetail> GetArticle(String uri) async { String article; List<String> comments; List<String> related; ... return ArticleDetail(article, comments, related); }
现在直接返回 Record 对象
Future<({String article, List comments, List related})> getArticle(String uri) async { String article; List<String> comments; List<String> related; ... return (article: article, comments: comments, related: related); }
void main(List<String> arguments) { final (:article, :comments, :related) = getArticle(123); }
今天讲了下 Record 的匿名、命名定义、赋值使用,以及使用场景,优点我总结如下:
:
冒号语法感谢阅读本文
如果有什么建议,请在评论中让我知道。我很乐意改进。
© 猫哥 ducafecat.com
end
Copyright 2024 ducafecat. All rights reserved.
微信: ducafecat, line: ducafecat,京ICP备2021009050号-3