PR

[Flutter]iOSのUITableViewのSectionのような表現ができるプラグイン

Flutter

はじめに

自作アプリを作っていてiOSのUITableViewのSectionのような表現がしたくなったので調べたところ、似た表現ができるプラグインを見つけたので紹介しようと思います。

環境

  • Flutter 2.2.0
  • group_list_view 1.1.1

実装方法

プラグインの最新バージョンを確認

下記のサイトにアクセスし、バージョンを確認します。

group_list_view | Flutter Package
Flutter package for ListView that allows you to group list items and support headers.

記事作成の時点では1.1.1が最新バージョンでした。

プラグインのインストール

pubspec.yamldependenciesに「group_list_view: ^1.1.1」を追記します。

または常に最新版を使う設定の「group_list_view: any」を追記します。

environment:
  sdk: ">=2.12.0 <3.0.0"

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
  group_list_view: any

その後、プロジェクト配下で「flutter pub get」コマンドを実行

よくわからない場合はAndroid Studiopubspec.yamlファイルを開くと右上に「Pub get」ボタンがあるのでそれを押して下さい。

サンプルコード

main.dart

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Map<String, List> _elements = {
    'Team A': ['Klay Lewis', 'Ehsan Woodard', 'River Bains'],
    'Team B': ['Toyah Downs', 'Tyla Kane'],
  };

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GroupListView(
        sectionsCount: _elements.keys.toList().length,
        countOfItemInSection: (int section) {
          return _elements.values.toList()[section].length;
        },
        itemBuilder: (BuildContext context, IndexPath index) {
          return ListTile(
            title: Text(
                '${_elements.values.toList()[index.section][index.index]}'),
          );
        },
        groupHeaderBuilder: (BuildContext context, int section) {
          return Container(
            color: Theme.of(context).accentColor,
            padding: const EdgeInsets.symmetric(horizontal: 10, vertical: 2),
            child: Text(
              _elements.keys.toList()[section],
              style: const TextStyle(fontSize: 18, fontWeight: FontWeight.w600),
            ),
          );
        },
        separatorBuilder: (context, index) => const Divider(),
      ),
    );
  }
}

結果

無事にUITableViewのSectionのような表現ができました。

さいごに

この機能はデフォルトでほしいところ

おすすめ参考書

コメント

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