Flutter: How to create Code Snippets? Json Serializable Snippet Example
While creating a Flutter App you must have come across some repetitive code. You might have tried checking out an extension for Flutter Snippets but it also doesn’t contain the snippet you want. For me personally, one of them was the code for box-shadow, writing it again and again, was burdensome. To resolve this we will learn how to create custom code snippets for Flutter in Visual Studio Code.
Procedure:
- Press
CTRL + SHIFT + P
and type Configure User Snippets and press Enter on the first option.
- Select
dart.json
from the list.
- For me the snippet file for dart.json was completely empty.
- I created the snippet that I always wanted. Now in any
.dart
file as soon as I type “pShadow” and pressEnter
the code is generated automatically.
{
"JSON Serializable": {
"prefix": "jsons",
"body": [
"import 'package:json_annotation/json_annotation.dart';",
"",
"part '${TM_FILENAME_BASE}.g.dart';",
"",
"@JsonSerializable()",
"class $1 {",
" $1();",
"",
" factory $1.fromJson(Map<String, dynamic> json) => _$${1}FromJson(json);",
"",
" Map<String, dynamic> toJson() => _$${1}ToJson(this);",
"}",
""
],
"description": "Generate code for JSON serialization and deserialization using json_serializable"
}
}
Here, “JSON Serializable” is the object key and should be unique across all the snippets. The prefix
is the name of the snippet and as soon as we write the name of the snippet, it is auto-suggested. The description is the descriptive text that explains what the snippet is about. The body is the real content of the snippet. If the line is single you can provide a string if it’s multi-line you can create a list of strings(as shown above).