Imports

A library in a programming language represents a collection of routines (set of programming instructions).

  1. Core libraries
  2. Dart has a rich set of core libraries that provide essentials for many everyday programming tasks such as working on collections of objects (dart:collection), making calculations (dart:math), and encoding/decoding data (dart:convert). Additional APIs are available in community contributed packages.


    The Dart core libraries that work on all Dart platforms:

        Dart:async : Support for asynchronous programming, with classes such as Future and Stream.

        Dart:collection : Classes and utilities that supplement the collection support in dart:core.

        Dart:convert : Encoders and decoders for converting between different data representations.

        Dart:core : Built-in types, collections, and other core functionality for every Dart program.

        Dart:developer : Interaction with developer tools such as the debugger and inspector.

        Dart:math : Mathematical constants and functions, plus a random number generator.

        Dart:typed_data : Lists that efficiently handle fixed sized data (for example, unsigned 8-byte integers) and SIMD numeric types.


    Example:

    import 'dart:math';

     

    void main() {

      print(cos(0.5));

      print(e);

      print(min(13 * 1211 * 14));

    }




    0.8775825618903728
    2.718281828459045
    154


    For more about the math library : Dart:Math


    If you import two libraries that have conflicting identifiers, then you can specify a prefix for one or both libraries using "as".

    Example:

    import 'dart:math' as math;

     

    void main() {

      print(math.sin(0.5));

      print(math.exp(4));

    }




    0.479425538604203
    54.598150033144236

  3. Importing Custom Libraries
  4. Dart also allows you to use your own code as a library.

    Example:

    File 1 :

    import 'dart:math';

     

    void printmax(int x, int y) {

      print("the max is ${max(x, y)}");

    }

     

    void printmin(int x, int y) {

      print("the min is ${min(x, y)}");

    }



    The main file in the same directory:

    import 'file1.dart';

     

    void main() {

      int a = 34, b = 50;

      printmax(a, b);

      printmin(a, b);

    }




    the max is 50
    the min is 34


    Note:

    If the two files are not within the same directory, we need to add the path:

    import 'dir/library_name' ;