1
/
5

IOT案件に参画

IOT案件に参画

レバテックさんのご紹介で2025年1月より参画

※良いところ

ライブラリに依存しないデザインパターンや自作を活用した開発が勉強になっている。

今では珍しい?

rxdartを使う機会があった。

直和表現なるものを知った。

Dart3.0から登場したsealed classで書いてみた。

// コンテンツの基底シールドクラス
sealed class Content {
  const Content();
}

// テキストコンテンツ
final class TextContent extends Content {
  final String text;
  
  const TextContent(this.text);
}

// イメージコンテンツ
final class ImageContent extends Content {
  final Uri url;
  
  const ImageContent(this.url);
}

// 使用例
void main() {
  // コンテンツのリスト
  final contents = [
    TextContent('テキストです'),
    ImageContent(Uri.parse('https://example.com/image.jpg')),
  ];

  // パターンマッチングでの処理
  for (final content in contents) {
    switch (content) {
      case TextContent(text: var text):
        print('テキスト: $text');
      case ImageContent(url: var url):
        print('画像URL: $url');
    }
  }

  // JSONからの変換例
  Content parseContent(Map<String, dynamic> json) {
    final text = json['text'] as String?;
    final url = json['url'] as String?;

    return switch ((text, url)) {
      (String text, null) => TextContent(text),
      (null, String url) => ImageContent(Uri.parse(url)),
      _ => throw FormatException('Invalid content format'),
    };
  }

  // JSONからの変換テスト
  final jsonExamples = [
    {'text': 'テキスト', 'url': null},
    {'text': null, 'url': 'https://...'},
  ];

  for (final json in jsonExamples) {
    try {
      final content = parseContent(json);
      print('パース結果: $content');
    } catch (e) {
      print('エラー: $e');
    }
  }
}



Like Hashimoto Junichi's Story
Let Hashimoto Junichi's company know you're interested in their content