Category: Dart

  • MySQL and Maria DB connection with Dart language

    MySQL and Maria DB connection with Dart language

    MySQL and Maria DB connection with Dart language

    Connect to MySQL or Maria DB server from Dart is very easy. We just need a couple of packages.

    Create your pubspec.yaml and add mysqli as a dependency. And run

    name: mysql
    description: A sample command-line application.
    # version: 1.0.0
    # homepage: https://www.example.com
    # author: sminrana <[email protected]>
    
    environment:
      sdk: '>=2.0.0 <3.0.0'
    
    dependencies:
      mysql1: ^0.17.1
    
    dev_dependencies:
      test: ^1.0.0
    
    pub get

    Create a file name main.dart which looks like this

    import 'dart:async';
    import 'dart:io';
    
    import 'package:mysql1/mysql1.dart';
    
    Future main() async {
      final conn = await MySqlConnection.connect(ConnectionSettings(
          host: 'localhost', port: 3306, user: 'root', password: '1234', db: 'database_name'));
    
    
      // Create a table
      await conn.query(
          'CREATE TABLE users (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255), email varchar(255), age int)');
    
      // Insert some data
      var result = await conn.query(
          'insert into users (name, email, age) values (?, ?, ?)',
          ['Bob', '[email protected]', 25]);
      print('Inserted row id=${result.insertId}');
    
      // Query the database using a parameterized query
      var results = await conn
          .query('select name, email from users where id = ?', [result.insertId]);
      for (var row in results) {
        print('Name: ${row[0]}, email: ${row[1]}');
      }
    
      // Finally, close the connection
      await conn.close();
    }
    
    

    Here Future main async as an asynchronous dart main function which is required due to async call on line 7, here we must wait for await MySqlConnection to be finished its process.

    Similarly we must wait for the task to be finished on line 12, we create a database table on this line.

    Finally run the code by

    dart main.dart
    Spread the love
  • Hello World in Dart Programming Language

    Read here if you haven’t yet install Dart in your system. Install Dart SDK on Mac, Windows and Linux.

    Download Visual Studio code for your OS.

    Install Dart plugin in your Visual Studio Editor. Just search Dart on your extensions page.

    Hello World in Dart Programming Language

    Now run this command on Mac ⌘ + Shift + P and type dart it will show this option to create a new project. Choose Console Application when it shows the Choose a Dart Template option.

    After creating the project your file explorer will look like this on Visual Studio Code.

    Under the bin directory, we are importing a library from lib directory which is being used as alias hello_world.

    and then main function has a print function that has a text ‘Hello world’ and called calculate() function from hellow_world library.

    The project can be found on github.

    Spread the love
  • Read CSV file by Dart

    Read CSV file by Dart

    Reading CSV files in Dart language is easy. Make sure you have already installed Dart SDK, follow this tutorial if you haven’t Install Dart SDK on Mac, Windows and Linux

    For this tutorial, we are going to use the Dart plugin on PHPStorm by JetBrains.  To install the plugin on Mac go to PHPStorm -> Preferences -> Plugins and search for ‘Dart’. See my screenshot.

    Read CSV file by Dart

    Few more plugins for Dart

    Dart for Visual Studio Code   and Dart Plugin from JetBrains

    After successfully installing the plugin open PHPStorm go to File -> New Project and choose Dart -> Console Application. See the screenshot.

    Read CSV file by Dart

    PHPStorm will give you a project structure like this. We won’t use the dummy dart library file from lib folder. We will use only main.dart file from the bin folder.

    Read CSV file by Dart

    Delete all lines from main.dart the file and paste this code. Run the code (bottom of the page) from PHPStorm it will print the id, symbol, and open column from each row of the CSV file.

    Download the CSV file for testing

    import 'dart:io';
    import 'dart:async';
    import 'dart:convert';
    
    main(List arguments) {
      final File file = new File("~/Downloads/C_stock_data.csv");
    
      Stream<List> inputStream = file.openRead();
    
      inputStream
          .transform(utf8.decoder)       // Decode bytes to UTF-8.
          .transform(new LineSplitter()) // Convert stream to individual lines.
          .listen((String line) {        // Process results.
    
           List row = line.split(','); // split by comma
    
            String id = row[0];
            String symbol = row[1];
            String open = row[2];
            String low = row[3];
            String high = row[4];
            String close = row[5];
            String volume = row[6];
            String exchange = row[7];
            String timestamp = row[8];
            String date = row[9];
    
            print('$id, $symbol, $open');
    
          },
          onDone: () { print('File is now closed.'); },
          onError: (e) { print(e.toString()); });
    }

    Download project from github

    Spread the love