PR

[Flutter]Flutter Widget of the Week「#163 Completers」、「#164 mix」、「#165 Uint8List」

Flutter

はじめに

前回はFlutter Widget of the Weekの「#160 List.generate」、「#161 Future.wait」、「#162 firebase_vertexai」を紹介しました。

今回はその続きで「#163 Completers」、「#164 mix」、「#165 Uint8List」の3つです。

前回の記事はこちら

またGitHubにも公開しています。

GitHub - nobushiueshi/flutter_widget_of_the_week
Contribute to nobushiueshi/flutter_widget_of_the_week development by creating an account on GitHub.

Flutter Widget of the Week

環境

  • Flutter 3.23.3

記事にした時点でのバージョンです。GitHubに公開しているのは常に最新の安定版(stable)を使う予定です。

#163 Completers

Completersとは?

Completerは、非同期処理の結果(値またはエラー)を後から手動で設定できるFutureを生成するための仕組みです。

Futureを即座に返すことができない非同期処理を、FutureベースのAPIに適合させたい場合に特に役立ちます。

サンプルコード

import 'dart:async';

import 'package:flutter/material.dart';

class SamplePage163 extends StatelessWidget {
  const SamplePage163({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Completers'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: FutureBuilder(
          future: Sample163Completer().result,
          builder: (context, snapshot) {
            if (snapshot.connectionState == ConnectionState.waiting) {
              return const Center(child: CircularProgressIndicator());
            } else if (snapshot.hasError) {
              return Center(child: Text('Error: ${snapshot.error}'));
            } else {
              return Center(child: Text('Result: ${snapshot.data}'));
            }
          },
        ),
      ),
    );
  }
}

class Sample163Completer {
  Sample163Completer() {
    Future.delayed(const Duration(seconds: 2), () {
      completer.complete('Operation completed');
    });
  }

  final Completer<String> completer = Completer<String>();

  Future<String> get result => completer.future;
}

結果

動画

公式リファレンス

Completer class - dart:async library - Dart API
API docs for the Completer class from the dart:async library, for the Dart programming language.

#164 mix

mixとは?

mixとは、ウィジェットのスタイルとレイアウトを効率的に管理するためのパッケージです。これにより、デザインの一貫性を保ちながら、再利用可能で柔軟なスタイリングシステムを構築できます。

サンプルコード

import 'package:flutter/material.dart';
import 'package:mix/mix.dart';

class SamplePage164 extends StatelessWidget {
  const SamplePage164({super.key});

  static final style = Style(
    $box.height(128),
    $box.width(128),
    $box.color.purple(),
    $box.borderRadius(16),
  );

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('mix'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Center(
          child: Box(
            style: style,
            child: const Center(
              child: Text(
                'mixを使った\nBox',
                style: TextStyle(
                  color: Colors.white,
                ),
                textAlign: TextAlign.center,
              ),
            ),
          ),
        ),
      ),
    );
  }
}

結果

動画

公式リファレンス

mix | Flutter package
An expressive way to effortlessly build design systems in Flutter.

#165 Uint8List

Uint8Listとは?

Uint8Listは、「符号なし8ビット整数のリスト」です。

簡単に言うと、0から255までの整数値を格納できるリストで、主に画像、音声、ファイル、ネットワーク通信などの「生のバイトデータ」を効率的に扱うために使われます。

具体的にはファイル操作や画像表示、ネットワーク通信、データ変換に使います。

サンプルコード

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class SamplePage165 extends StatelessWidget {
  const SamplePage165({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Uint8List'),
        centerTitle: true,
      ),
      body: SafeArea(
        child: Center(
          child: FutureBuilder(
            future: _loadAsset('assets/sample.png'),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return Text('Error: ${snapshot.error}');
              }

              return Image.memory(snapshot.data!);
            },
          ),
        ),
      ),
    );
  }

  Future<Uint8List> _loadAsset(String path) async {
    final data = await rootBundle.load(path);
    return data.buffer.asUint8List();
  }
}

結果

動画

公式リファレンス

Uint8List class - dart:typed_data library - Dart API
API docs for the Uint8List class from the dart:typed_data library, for the Dart programming language.

さいごに

またサボってしまっていた。。。

おすすめ参考書

リンク

GitHub - nobushiueshi/flutter_widget_of_the_week
Contribute to nobushiueshi/flutter_widget_of_the_week development by creating an account on GitHub.

コメント

タイトルとURLをコピーしました