LOGICKY BLOG

PHP、Javascript、Python等のプログラミングに関するブログです

Flutterでリストビュー(ListView)使ってみる

これを参考にやってみました。

github.com

github.com

f:id:edo1z:20190826190434p:plain

lib/pages/menu_list.dart

import 'package:flutter/material.dart';
import 'package:hoge/menu_list/menu_list.dart';
import 'package:hoge/menu_list/model/menu.dart';

class MenuListScreen extends StatelessWidget {
  _buildMenuList() {
    return <MenuModel>[
      const MenuModel(type: 'FOOD', name: '焼きそば', price: 400),
      const MenuModel(type: 'FOOD', name: 'たこ焼き', price: 500),
      const MenuModel(type: 'DRINK', name: '生ビール', price: 400),
      const MenuModel(type: 'DRINK', name: 'ウーロン茶', price: 150),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(body: MenuList(_buildMenuList()));
  }
}

lib/menu_list/menu_list.dart

import 'package:flutter/material.dart';
import 'package:hoge/menu_list/menu_list_item.dart';
import 'package:hoge/menu_list/model/menu.dart';

class MenuList extends StatelessWidget {
  final List<MenuModel> _menuModel;

  MenuList(this._menuModel);

  @override
  Widget build(BuildContext context) {
    return ListView(
      padding: EdgeInsets.symmetric(vertical: 8.0),
      children: _buildMenuList(),
    );
  }

  List<MenuListItem> _buildMenuList() {
    return _menuModel
        .map((menu) => MenuListItem(menu))
        .toList();
  }
}

lib/menu_list/menu_list_item.dart

import 'package:flutter/material.dart';
import 'package:hoge/menu_list/model/menu.dart';

class MenuListItem extends StatelessWidget {
  final MenuModel _menuModel;

  MenuListItem(this._menuModel);

  @override
  Widget build(BuildContext context) {
    return ListTile(
        leading: CircleAvatar(child: Text(_menuModel.name[0])),
        title: Text(_menuModel.name),
        subtitle: Text(_menuModel.type));
  }
}

lib/menu_list/model/menu.dart

class MenuModel {
  final String type;
  final String name;
  final int price;

  const MenuModel({this.type, this.name, this.price});
}