0
点赞
收藏
分享

微信扫一扫

dart注释以及json解编码


作者:坚果

公众号:"​​大前端之旅​​"

华为云享专家,InfoQ签约作者,OpenHarmony布道师,,华为云享专家,阿里云专家博主,51CTO博客首席体验官,​​开源项目GVA成员之一​​,专注于大前端技术的分享,包括Flutter,鸿蒙,小程序,安卓,VUE,JavaScript。

如何在 Flutter & Dart 中使用注释

这是一篇关于 Flutter 和 Dart 注释的简明文章。

单行注释(格式注释)

只需在要注释掉的行的开头放置两个斜杠符号即可。

// This is a comment
print('abc');

多行注释(块注释)

句法:

/* ... */

该方法通常用于注释掉一段代码,如下所示:

/*
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kindacode.com'),
),
body: Center(),
);
}
}
*/

文档注释

使用 DOC 注释允许​​dartdoc​​库根据您的注释内容自动为您的代码生成文档。

例子:

/// Deletes the file at [path].
/// Throws an [IOError] if the file could not be found.

在 Visual Studio Code 中使用热键

如果您使用的是 Visual Studio Code,则可以使用键盘快捷键注释掉一行或一段代码。只需用鼠标选择要评论的行,然后按以下组合键:

  • 如果您使用的是 Windows,请按Ctrl+K然后按Ctrl+C
  • 如果您在 Mac 上,请按Command+K然后按Command+C

要取消注释代码块,请使用鼠标选择它,然后使用以下组合键:

  • Ctrl+K然后Ctrl+U如果你在 Windows 上
  • 如果您在 Mac 上,则Command+K然后Command+U

您还可以按 Ctrl + / (Windows)、Command + / (Mac) 来切换。

如何在 Flutter 中编码/解码 JSON

速记

本文将向您展示如何在 Flutter 中对 JSON 进行编码/解码。您需要遵循的步骤是:

1.导入dart:convert库:

import 'dart:convert';

2.使用:

  • json.encode()jsonEncode()用于编码。
  • json.decode()jsonDecode()用于解码。

例子

示例 1:JSON 编码

import 'dart:convert';

void main() {
final products = [
{'id': 1, 'name': 'Product #1'},
{'id': 2, 'name': 'Product #2'}
];

print(json.encode(products));
}

输出:

[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]

示例 2:JSON 解码

import 'dart:convert';
import 'package:flutter/foundation.dart';

void main() {
const String responseData =
'[{"id":1,"name":"Product #1"},{"id":2,"name":"Product #2"}]';

final products = json.decode(responseData);

if (kDebugMode) {
// Print the type of "products"
print(products.runtimeType);

// Print the name of the second product in the list
print(products[1]['name']);
}
}

输出:

List<dynamic>
Product #2

希望这可以帮助到你。

举报

相关推荐

0 条评论