Dart Fundamentals

Dart Fundamentals

Master the Art of Flutter

Dart is the programming language used to develop Flutter apps. It is a modern, object-oriented language that is easy to learn and use.

Variables, data types, and operators

A variable is a named location in memory where you can store a value. To declare a variable in Dart, you use the var keyword followed by the name of the variable and the type of data that it will store. For example, the following code declares a variable called name that will store a string:

var name = 'John Doe';

Dart supports a variety of data types, including:

  • int: Integers

  • double: Floating-point numbers

  • String: Strings

  • bool: Boolean values

  • dynamic: Values of any type

Dart also provides a number of operators that can be used to manipulate data. For example, the following code adds two integers together:

var sum = 1 + 2;

Control flow statements

Control flow statements allow you to control the flow of execution of your program. Dart provides a number of control flow statements, including:

  • if: Executes a code block if a condition is met.

  • else: Executes a code block if a condition is not met.

  • switch: Executes a code block based on the value of a variable.

  • for: Executes a code block repeatedly until a condition is met.

  • while: Executes a code block repeatedly until a condition is met.

Functions

Functions allow you to group together related code and reuse it throughout your program. To define a function in Dart, you use the function keyword followed by the name of the function and the parameters that it accepts. The body of the function contains the code that will be executed when the function is called.

For example, the following code defines a function called greet() that takes a name as a parameter and returns a greeting message:

function greet(name) {
  return 'Hello, $name!';
}

To call the greet() function, you would use the following syntax:

var greeting = greet('John Doe');

The greeting variable will now contain the following value:

'Hello, John Doe!'

Classes and objects

Classes and objects are the foundation of object-oriented programming. A class is a blueprint for creating objects. An object is an instance of a class.

To define a class in Dart, you use the class keyword followed by the name of the class and the body of the class. The body of the class contains the properties and methods of the class.

For example, the following code defines a class called Person with two properties, name and age:

class Person {
  String name;
  int age;

  Person(this.name, this.age);
}

To create an instance of the Person class, you would use the following syntax:

var person = Person('John Doe', 30);

The person variable will now contain an object of the Person class.

Generics

Generics allow you to write code that is more flexible and reusable. Generics allow you to pass data types as parameters to functions and classes.

For example, the following code defines a function called max() that takes two values of any type and returns the larger value:

function max<T>(T a, T b) {
  if (a > b) {
    return a;
  } else {
    return b;
  }
}

This function can be used to find the larger value of any two data types, such as integers, doubles, or strings.

Async/await

Async/await is a feature of Dart that allows you to write asynchronous code in a synchronous way. This can make your code more readable and maintainable.

To use async/await, you first need to mark your function as asynchronous using the async keyword. You can then use the await keyword to wait for asynchronous operations to complete.

For example, the following code defines an asynchronous function called fetchPosts() that fetches a list of posts from a server:

async function fetchPosts() {
  final response = await http.get('<https://example.com/posts>');

  if (response.statusCode == 200) {
    final data = jsonDecode(response.body);
    return data;
  } else {
    throw Exception('Failed to fetch posts');
  }
}

This function will first make an HTTP GET request to the server. It will then use the await keyword to wait for the response to be returned. Once the response has been returned, the function will decode the JSON response and return the list of posts.

To call the fetchPosts() function, you would use the following syntax:

var posts = await fetchPosts();

The posts variable will now contain the list of posts that were fetched from the server.

Async/await can be used to make any asynchronous operation synchronous, such as fetching data from a server, reading a file, or performing a long-running operation.

Here is an example of how to use async/await to fetch a list of posts from a server and display them in a ListView:

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class PostList extends StatefulWidget {
  @override
  _PostListState createState() => _PostListState();
}

class _PostListState extends State<PostList> {
  List<Post> posts = [];

  @override
  void initState() {
    super.initState();

    fetchPosts();
  }

  Future<void> fetchPosts() async {
    final response = await http.get('<https://example.com/posts>');

    if (response.statusCode == 200) {
      final data = jsonDecode(response.body);
      posts = data.map((post) => Post.fromJson(post)).toList();
    }

    setState(() {});
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Post List'),
      ),
      body: ListView.builder(
        itemCount: posts.length,
        itemBuilder: (context, index) {
          final post = posts[index];

          return ListTile(
            title: Text(post.title),
            subtitle: Text(post.body),
          );
        },
      ),
    );
  }
}

class Post {
  final int id;
  final String title;
  final String body;

  Post.fromJson(Map<String, dynamic> json)
      : id = json['id'],
        title = json['title'],
        body = json['body'];
}

This code will first make an HTTP GET request to the server to fetch the list of posts. It will then use the await keyword to wait for the response to be returned. Once the response has been returned, the code will decode the JSON response and populate the posts list with the list of posts.

The code will then rebuild the widget, which will display the list of posts in a ListView.

Async/await is a powerful feature of Dart that can make your code more readable and maintainable. It allows you to write asynchronous code in a synchronous way, which can make your code easier to reason about and debug.

In the next article, I will introduce you to the building blocks of Flutter apps: Widgets.