Q&D: Dart에서 문자열 및 반복 가능

작성자

카테고리:

← 피드로
DEV Community · Mathieu Kerjouan · 2026-08-25 개발(SW)

By default, Strings in Dart can’t be used as Iterable, they must be converted to a List<int> or another kind of Iterable class. To do that, one must import the dart:convert module and start playing with the converters.

A pure ASCII string can be converted using ascii.encode(str), where str is the String to convert to List<int>.

import 'dart:convert';

void main() {
  final str = "hello world";
  for (var c in ascii.encode(str)) {
    print("${c} (${String.fromCharCode(c)})");
  }
}

Enter fullscreen mode Exit fullscreen mode

$ dart run
104 (h)
101 (e)
108 (l)
108 (l)
111 (o)
32 ( )
119 (w)
111 (o)
114 (r)
108 (l)
100 (d)

Enter fullscreen mode Exit fullscreen mode

The same can be done with utf8 Strings as well.

import 'dart:convert';

void main() {
  final str = "波動拳: ↓↙←Ⓑ";
  for (var c in utf8.encode(str)) {
    print("${c} (${String.fromCharCode(c)})");
  }
}

Enter fullscreen mode Exit fullscreen mode

$ dart run
230 (æ)
179 (³)
162 (¢)
229 (å)
139 ()
149 ()
230 (æ)
139 ()
179 (³)
58 (:)
32 ( )
226 (â)
134 ()
147 ()
226 (â)
134 ()
153 ()
226 (â)
134 ()
144 (
226 (â)
146 ()
183 (·)

Enter fullscreen mode Exit fullscreen mode

This output is “normal”, because an utf8 character is encoded on 8, 16 or 32 bits, but the encoder will encode it only on 8 bits. This means an utf8 character will be split in more than one byte. A quick and dirty solution to avoid this issue is to use the String.split() method and iterate over the List generated.

void main() {
  final str = "波動拳: ↓↙←Ⓑ";
  for (var c in str.split("")) {
    print("${c} : ${utf8.encode(c)}");
  }
}

Enter fullscreen mode Exit fullscreen mode

$ dart run
波 : [230, 179, 162]
動 : [229, 139, 149]
拳 : [230, 139, 179]
: : [58]
  : [32]
↓ : [226, 134, 147]
↙ : [226, 134, 153]
← : [226, 134, 144]
Ⓑ : [226, 146, 183]

Enter fullscreen mode Exit fullscreen mode

The 波 character is made of 3 integers [230, 179, 162], like the rest of the unicode characters displayed. Here a list of resources talking about that:

Cover Image by Julian Schultz on Unsplash

원문에서 계속 ↗