🕒

timelinesなるものを使ってみた!

2023/01/11に公開

棒線がつながっているあれ!

棒線と丸がつながっているあれ、タイムラインと呼ぶみたいです。
タイムライン」とは、「時系列にしたがって経過し変化する情報を表示したもの」という意味だとか?
こちらのタイムラインとは何か記事に詳しく書かれています。
https://gakumado.mynavi.jp/gmd/articles/54003

今回使用するpackage
https://pub.dev/packages/timelines

packageについてですが、どうやらまだ試作品ということですかね?
でもLike数は多い!
解説を日本語に翻訳

Flutterのためのパワフルで使いやすいタイムラインパッケージ! 🚀

警告: このパッケージは初期段階です。安定性を保証するためのテストはまだ十分ではありません。一部のAPIは変更される可能性があります。

ページ下のWidgetの解説
タイムライン
タイムラインコンポーネントにはScrollViewに似たTimelineとFlexに似たFixedTimelineの2つのウィジェットがあります。

また、コンストラクターもScrollViewやFlexと同様です。

主な違いは TimelineTheme を祖先として持っていることです。

tileBuilder コンストラクタは TimelineTileBuilder を使ってより強力な機能を提供します。

TimelineTileBuilderが必要ない場合は、ListView、Column、Rowなどの他のflutter widgetを使うことができる。

flutterウィジェットを使う場合でも、TimelineThemeを使うことができます。

結論

どう使えばいいのか?
数ヶ月前までわからなかったのですが、Listを使ってTimelineTileBuilderにデータを与えて、描画すれば外部のデータを渡すことができるようです。
今回は簡単なサンプルを作ってみました。

今回のファイル構成

lib
├── firebase_options.dart
├── main.dart
└── model
    ├── flow.dart
    ├── flow.freezed.dart
    ├── flow.g.dart
    └── provider.dart

modelディレクトリに、Listを使ってTimelineTileBuilderに渡すロジックが書かれています。
ListViewBuilderと同じようなものだと思ってください。
やることは一緒で、Listを使えばClassのプロパティのnameやnumberといった値を渡せる。
他には、これが電車に関係したアプリだったら、Classにstationとか書けば、今ここの駅にいますよというのがわかるようになりますね。

今回は、Classを使ってモデルを作るのに、便利なFreezedを使用します。toJOSNやformJSONを自分で作らなくて良くなるので楽です。
後は、StreamProviderを使ってFireStoreの全ての値を渡して画面に表示するだけです。
TimelineTileBuilderが今回は、ListViewBuilderと同じ役割を果たします。

必要なpackageを追加する

pubspec.yaml
name: timelineview_app
description: A new Flutter project.

# The following line prevents the package from being accidentally published to
# pub.dev using `flutter pub publish`. This is preferred for private packages.
publish_to: 'none' # Remove this line if you wish to publish to pub.dev

# The following defines the version and build number for your application.
# A version number is three numbers separated by dots, like 1.2.43
# followed by an optional build number separated by a +.
# Both the version and the builder number may be overridden in flutter
# build by specifying --build-name and --build-number, respectively.
# In Android, build-name is used as versionName while build-number used as versionCode.
# Read more about Android versioning at https://developer.android.com/studio/publish/versioning
# In iOS, build-name is used as CFBundleShortVersionString while build-number is used as CFBundleVersion.
# Read more about iOS versioning at
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.0+1

environment:
  sdk: '>=2.18.0 <3.0.0'

# Dependencies specify other packages that your package needs in order to work.
# To automatically upgrade your package dependencies to the latest versions
# consider running `flutter pub upgrade --major-versions`. Alternatively,
# dependencies can be manually updated by changing the version numbers below to
# the latest version available on pub.dev. To see which dependencies have newer
# versions available, run `flutter pub outdated`.
dependencies:
  flutter:
    sdk: flutter


  # The following adds the Cupertino Icons font to your application.
  # Use with the CupertinoIcons class for iOS style icons.
  cupertino_icons: ^1.0.2
  timelineview: ^1.0.2
  timelines: ^0.1.0
  flutter_riverpod: ^2.1.1
  firebase_core: ^2.4.0
  cloud_firestore: ^4.2.0
  json_annotation: ^4.7.0
  freezed_annotation: ^2.2.0

dev_dependencies:
  flutter_test:
    sdk: flutter

  # The "flutter_lints" package below contains a set of recommended lints to
  # encourage good coding practices. The lint set provided by the package is
  # activated in the `analysis_options.yaml` file located at the root of your
  # package. See that file for information about deactivating specific lint
  # rules and activating additional ones.
  flutter_lints: ^2.0.0
  json_serializable: ^6.5.4
  freezed: ^2.3.2
  build_runner: ^2.3.3

# For information on the generic Dart part of this file, see the
# following page: https://dart.dev/tools/pub/pubspec

# The following section is specific to Flutter packages.
flutter:

  # The following line ensures that the Material Icons font is
  # included with your application, so that you can use the icons in
  # the material Icons class.
  uses-material-design: true

  # To add assets to your application, add an assets section, like this:
  # assets:
  #   - images/a_dot_burr.jpeg
  #   - images/a_dot_ham.jpeg

  # An image asset can refer to one or more resolution-specific "variants", see
  # https://flutter.dev/assets-and-images/#resolution-aware

  # For details regarding adding assets from package dependencies, see
  # https://flutter.dev/assets-and-images/#from-packages

  # To add custom fonts to your application, add a fonts section here,
  # in this "flutter" section. Each entry in this list should have a
  # "family" key with the font family name, and a "fonts" key with a
  # list giving the asset and other descriptors for the font. For
  # example:
  # fonts:
  #   - family: Schyler
  #     fonts:
  #       - asset: fonts/Schyler-Regular.ttf
  #       - asset: fonts/Schyler-Italic.ttf
  #         style: italic
  #   - family: Trajan Pro
  #     fonts:
  #       - asset: fonts/TrajanPro.ttf
  #       - asset: fonts/TrajanPro_Bold.ttf
  #         weight: 700
  #
  # For details regarding fonts from package dependencies,
  # see https://flutter.dev/custom-fonts/#from-packages

Listで使うモデルクラス

model/flow.dart
import 'package:freezed_annotation/freezed_annotation.dart';
import 'package:flutter/foundation.dart';

part 'flow.freezed.dart';
part 'flow.g.dart';


class FlowChart with _$FlowChart {
  const factory FlowChart({
    required String name,
    required int number,
  }) = _FlowChart;

  factory FlowChart.fromJson(Map<String, dynamic> json) =>
      _$FlowChartFromJson(json);
}

コマンドを実行してファイルを自動生成する

flutter pub run build_runner build

Providerを定義する
FireStoreのデータを取得するProvider
StreamProviderで全てのデータを取得する。number1から順番に表示したいので、orderByを使う。

model/provider.dart
import 'dart:developer';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:timelineview_app/model/flow.dart';

/// リストでFlowChartクラスを型に使いプロパティを使えるようにする.
final usersStreamProvider = StreamProvider<List<FlowChart>>((ref) {
  // FireStoreの全てのデータを取得.
  // 昇順で表示できるようにorderByを使用。[1~3]の順にダミーデータを表示.
  final collection = FirebaseFirestore.instance
      .collection('users')
      .orderBy('number', descending: false);
  // データ(Map型)を取得.
  final stream = collection.snapshots().map(
        // CollectionのデータからUserクラスを生成する.
        (e) => e.docs.map((e) => FlowChart.fromJson(e.data())).toList(),
      );
  return stream;
});

今回使用するダミーデータ
今回は画面に描画するのが目的なので、usersというコレクションを作成して、ドキュメントを3つ作成しnameフィールドと、numberフィールドを用意します。
Listで画面にFireStoreのデータを表示するときは、先ほど作成したFlowChartクラスのプロパティを使用します。

FireStoreのダミーデータのデータ型

name: string
number: int

スクリーンショット

画面にデータを描画する

main.dartに、timelinesのコードを書いて、画面に描画してみましょう。
Indicatorと呼ばれている表示板の物体?、線を点々にしたり、丸を四角にできます。
種類が色々あるので、好みのものに変えて、楽しんでください!

公式のコード

ContainerIndicator
四角の物体を作る.

ContainerIndicator(
  child: Container(
    width: 15.0,
    height: 15.0,
    color: Colors.blue,
  ),
)

DashedLineConnector
破線を作る。

SizedBox(
  height: 20.0,
  child: DashedLineConnector(),
)

今回は、標準的な丸と棒線にしました。
このコードを使って、ダミーのデータを描画してもらいます。

main.dart
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:timelines/timelines.dart';
import 'package:timelineview_app/firebase_options.dart';
import 'package:timelineview_app/model/provider.dart';

void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(ProviderScope(child: const MyApp()));
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.cyan,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends ConsumerWidget {
  const MyHomePage({Key? key}) : super(key: key);

  
  Widget build(BuildContext context, WidgetRef ref) {
    // StreamProviderを読み取る(取得できる型は `AsyncValue<T>`)
    final users = ref.watch(usersStreamProvider);

    return Scaffold(
      appBar: AppBar(
        title: Text('timeline'),
      ),
      // AsyncValue は `.when` を使ってハンドリングする
      body: users.when(
          // 処理中は `loading` で指定したWidgetが表示される
          loading: () => const CircularProgressIndicator(),
          // エラーが発生した場合に表示されるWidgetを指定
          error: (error, stack) => Text('Error: $error'),
          // 取得した `users` が `data` で使用できる
          data: (user) {
            return Column(
              children: [
                SizedBox(height: 50),
                Expanded(
                  child: Timeline.tileBuilder(
                    // ListViewBuilderと同じように使用.
                    builder: TimelineTileBuilder.fromStyle(
                      contentsAlign: ContentsAlign.alternating,
                      contentsBuilder: (context, index) => Padding(
                        padding: const EdgeInsets.all(24.0),
                        child: Column(// 縦に番号と名前を並べる.
                          children: [
                            Text(user[index].number.toString()),// numberプロパティ.
                            Card(
                                child: Container(
                                    padding: EdgeInsets.all(8.0),
                                    child: Text(user[index].name))),// nameプロパティ.
                          ],
                        ),
                      ),
                      itemCount: user.length,// Listで渡されたデータを数える.
                    ),
                  ),
                ),
              ],
            );
          }),
    );
  }
}

こんな感じで表示することができました

やってみた感想

以前は何故できなかったのだろうと考えてわかったのですが、単純にListとWidgetの知識がないからでした。
学べる環境が整っていればもっと速く覚えられたのではないかな〜と思っております。

Flutter大学

Discussion