How to Use Annotations in Flutter & Dart

How to use annotations in Flutter & Dart

This is a concise article on Flutter and Dart annotations.

Single Line Comments (Format Comments)

Just put two slash symbols at the beginning of the line you want to comment out.

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

Multi-line comments (block comments)

syntax:

/* ... */

This method is often used to comment out a piece of code like this:

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

Documentation comments

Using DOC comments allows the dartdoc library to automatically generate documentation for your code based on the content of your comments.

example:

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

Use hotkeys in Visual Studio Code

If you’re using Visual Studio Code, you can use keyboard shortcuts to comment out a line or block of code. Just select the line you want to comment with your mouse and press the following key combination:

  • If you are using Windows, press Ctrl + K then Ctrl + C

  • If you’re on a Mac, press Command + K then Command + C

To uncomment a block of code, select it with the mouse, then use the following key combinations:

  • Ctrl + K then Ctrl + U if you are on Windows

  • If you’re on a Mac, Command + K then Command + U

You can also switch by pressing Ctrl + / (Windows), Command + / (Mac).

How to encode/decode JSON in Flutter

shorthand

This article will show you how to encode/decode JSON in Flutter. The steps you need to follow are:

1. Import the dart:convert library:

import 'dart:convert';

2. Use:

  • json.encode() or jsonEncode() for encoding.

  • json.decode() or jsonDecode() for decoding.

example

Example 1: JSON encoding

import 'dart:convert';void main() {
  final products = [
    {'id': 1, 'name': 'Product #1'},
    {'id': 2, 'name': 'Product #2'}
  ];print(json.encode(products));
}

output:

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

Example 2: JSON decoding

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']);
  }
}

output:

List<dynamic>
Product #2

Hope this helps you.

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *