상세 컨텐츠

본문 제목

Dart How To

Dart

by techbard 2024. 1. 16. 10:15

본문

반응형
import 'dart:math';

void main(List<String> args) {
  // Generate Random Number
  Random random = Random();
  num rNumInt = random.nextInt(10);
  print("Generated Random Number\n between 0 to 9 =>\n  $rNumInt");
  print("");
  num rNumDouble = random.nextDouble();
  print("Generated Random Number\n between 0.01 to 1.00 =>\n  $rNumDouble");
  print("");

  // Generate Random Number Between Any Number
  // fomula: min + Random().nextInt((max + 1) - min);

  int min = 1;
  int max = 10;

  int rndNumBetween1To10 = min + Random().nextInt((max + 1) - min);
  print(
      "Generated Random number\n between $min and $max =>\n  $rndNumBetween1To10");
}

/*

Backend means an application runs on a server and 
can handle client requests. 
It can accept requests from a client, 
process them and respond to the client. 
Currently, many technologies provide a backend 
to clients, such as golang, node js, PHP, python, java, .net, etc.

*/

// 결과
Generated Random Number
 between 0 to 9 =>
  1
Generated Random Number
 between 0.01 to 1.00 =>
  0.24494158501157814

Generated Random number
 between 1 and 10 =>
  7

 

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

/* including this in pubspec.yaml
  dependencies:
    http: ^0.13.5
*/

/*
Note: If the status code is 200, it means the request is successful 
and you can get the response body otherwise the request is failed 
and you can get error message.
*/

// Make HTTP Get Request
void main(List<String> args) async {
  var url = Uri.parse('https://jsonplaceholder.typicode.com/posts/1');
  var response = await http.get(url);

  if (response.statusCode == 200) {
    print(response.body);
  } else {
    print('Request failed with status code: ${response.statusCode}');
  }
}

/*
HTTP request means sending a request to a server and getting a response from the server.
*/

// 결과
{
  "userId": 1,
  "id": 1,
  "title": "sunt aut facere repellat provident occaecati excepturi optio reprehenderit",
  "body": "quia et suscipit\nsuscipit recusandae consequuntur expedita et cum\nreprehenderit molestiae ut ut quas totam\nnostrum rerum est autem sunt rem eveniet architecto"
}

 

import 'dart:io';

// read CSV file

// CSV example
// "Code With Andrea","03/01/2019 23:00","04/01/2019 00:30","1.5","","Blogging","","","",""

void main(List<String> args) {
  if (args.isEmpty) {
    print('Usage: dart totals.dart <inputFile.csv>');
    exit(1);
  }

  final inputFile = args.first;
  final lines = File(inputFile).readAsLinesSync();
  lines.removeAt(0); // header of CSV removed.
  final Map<String, double> totalDurationBytag = {};

  var totalDuration = 0.0;
  for (var line in lines) {
    final values = line.split(',');
    final durationStr = values[3].replaceAll('"', '');
    final duration = double.parse(durationStr);
    final tag = values[5].replaceAll('"', '');
    final previousTotal = totalDurationBytag[tag];
    if (previousTotal == null) {
      totalDurationBytag[tag] = duration;
    } else {
      totalDurationBytag[tag] = previousTotal + duration;
    }
    totalDuration += duration;
  }

  for (var entry in totalDurationBytag.entries) {
    final durationFormatted = entry.value.toStringAsFixed(1);
    final tag = entry.key == '' ? 'Unallocated' : entry.key;
    print('$tag: ${durationFormatted}h');
  }

  print('==========' * 3);
  print('Total for all tags: ${totalDuration.toStringAsFixed(1)}h');
}

/*
We need a command line argument, that represents the path to a
CSV file that we want to process.

CSV: Comma Seperated Value

Note: It should be invalid to run the program without arguments.
We need to write some defensive code so that the program can fail
gracefully.

Note: program should terminate immediately when called without arguments.

By convention:
  - zero error code on success.
  - non-zero error code on failure.
*/

// 결과
Blogging: 62.9h
Flutter Firebase Course: 393.9h
Unallocated: 52.4h
YouTube Production: 166.0h
Community engagement: 54.5h
Development: 83.1h
Promotion: 25.2h                   
Website / Setup: 66.2h
BizDev / Sponsors: 2.0h      
Analytics / Growth: 14.7h
Admin: 1.6h
Client Leads: 1.7h
============================== 
Total for all tags: 924.2h

 

/*
Top tip
  - Write high-level flow with pseudocode
  - Identify main steps without worrying about the details

* Use stdin to read user input from console
* import dart:io to use it

* Use stdin, stdout variables for console I/O

*/

import 'dart:io';
import 'dart:math';

enum Move { rock, paper, scissors }

void main(List<String> args) {
  final rng = Random();

  while (true) {
    stdout.write('Rock, paper or scissors? (r/p/s) ');
    final input = stdin.readLineSync();
    if (input == 'r' || input == 'p' || input == 's') {
      var playerMove;
      if (input == 'r') {
        playerMove = Move.rock;
      } else if (input == 'p') {
        playerMove = Move.paper;
      } else {
        playerMove = Move.scissors;
      }

      final random = rng.nextInt(3);
      final aiMove = Move.values.elementAt(random);

      print('You played: $playerMove');
      print('AI played: $aiMove');

      if (playerMove == aiMove) {
        print("It's a draw.");
      } else if (playerMove == Move.rock && aiMove == Move.scissors ||
          playerMove == Move.paper && aiMove == Move.rock ||
          playerMove == Move.scissors && aiMove == Move.paper) {
        print("You win.");
      } else {
        print("You lose.");
      }

      // print('You selected: $input');
    } else if (input == 'q') {
      break;
    } else {
      print('Invalid input.');
    }
  }
}

// 결과
Rock, paper or scissors? (r/p/s) p
You played: Move.paper
AI played: Move.rock
You win.
Rock, paper or scissors? (r/p/s) s
You played: Move.scissors        
AI played: Move.paper
You win.
Rock, paper or scissors? (r/p/s) r
You played: Move.rock
AI played: Move.rock
It's a draw.
Rock, paper or scissors? (r/p/s) p
You played: Move.paper
AI played: Move.scissors
You lose.
반응형

관련글 더보기

댓글 영역