Flutter学习日记-仿iOS Tableview风格布局

Flutter for 定位布局

-先看效果图


image.png

1.自定义数据源 (随便添加了几个)

import 'package:flutter/material.dart';

class RegionVo {
  String sectionKey;
  String name;

  RegionVo({@required this.sectionKey,this.name});
}

List<RegionVo> regionDataSource = [
  new RegionVo(
      sectionKey: 'A',
      name: '阿拉善',
    ),
  new RegionVo(
      sectionKey: 'A',
      name: '安庆市',
    ),
  new RegionVo(
      sectionKey: 'A',
      name: '安阳市',
    ),
  new RegionVo(
      sectionKey: 'B',
      name: '北京',
    ),  
  new RegionVo(
      sectionKey: 'B',
      name: '包头市',
    ),
  new RegionVo(
      sectionKey: 'C',
      name: '承德市',
    ),
    new RegionVo(
      sectionKey: 'C',
      name: '沧州市',
    ),
  new RegionVo(
      sectionKey: 'C',
      name: '池州',
    ),
    new RegionVo(
      sectionKey: 'C',
      name: '长阳',
    ),
  new RegionVo(
      sectionKey: 'D',
      name: '德州',
    ),
    new RegionVo(
      sectionKey: 'D',
      name: '达州',
    ),
  new RegionVo(
      sectionKey: 'D',
      name: '定西市',
    ),
];

2.自定义一个header项

import 'package:flutter/material.dart';
import '../Common/touch_callback.dart';

class RegionHeader extends StatelessWidget {
  final String title;
  RegionHeader({Key key, @required this.title});

  @override
  Widget build(BuildContext context) {
    return Container(
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
                bottom: BorderSide(width: 0.5, color: Colors.grey[100]))),
        height: 64.0,
        child: TouchCallBack(
          onPressed: (){},
          isfeed: true,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              Container(
                margin: EdgeInsets.only(left: 12.0, right: 12.0),
                child: Image.asset(
                  'images/location.png',
                  width: 32,
                  height: 32,
                ),
              ),
              Expanded(
                  child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text(title),
                ],
              )),
            ],
          ),
        ));
  }
}

3.自定义一个item项

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

class RegionItem extends StatelessWidget {
  final RegionVo item;
  final String titleName;

  RegionItem({this.item, this.titleName});

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 0.5, color: Color(0xFFd9d9d9)))),
      height: 52.0,
      child: FlatButton(
        onPressed: () {},
        child: Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(left: 12.0),
              // color: Colors.grey,
              child: Text(
                titleName == null ? item.name ?? '暂时' : titleName,
                style: TextStyle(fontSize: 18.0, color: Colors.black),
              ),
            )
          ],
        ),
      ),
    );
  }
}

4.接下来就是自定义一个列表项(构建三个builder 给外部调用)

import 'package:flutter/material.dart';
import 'package:region/region/region_data.dart';

class RegionList extends StatefulWidget {
  final List<RegionVo> items;
  final IndexedWidgetBuilder headerBuild;
  final IndexedWidgetBuilder sectionBuild;
  final IndexedWidgetBuilder itemsBuild;

  RegionList({
    Key key,
    @required this.items,
    this.headerBuild,
    @required  this.sectionBuild,
    @required  this.itemsBuild
  }) : super(key: key);

  @override
  RegionListState createState() => new RegionListState();
}

class RegionListState extends State<RegionList> implements SectionInderxer {
  Color _pressColor = Colors.transparent;
  final ScrollController _scrollController = new ScrollController();

  bool _onNotification(ScrollNotification notification) {
    return true;
  }

  _isShowHeader(index) {
    if (index == 0 && widget.headerBuild != null) {
      return Offstage(
        offstage: false,
        child: widget.headerBuild(context, index),
      );
    }
    return Container();
  }

  bool _shouldShowSectionHeader(index) {
    if (index < 0) {
      return false;
    }
    if (index == 0) {
      return false;
    }
    if (index != 0 &&
        widget.items[index].sectionKey != widget.items[index - 1].sectionKey) {
      return false;
    }
    return true;
  }

  @override
  Widget build(BuildContext context) {
    
    return Scaffold(
      body: Stack(
        children: <Widget>[
          NotificationListener(
            onNotification: _onNotification,
            child: ListView.builder(
              controller: _scrollController,
              physics: const AlwaysScrollableScrollPhysics(),
              itemCount: widget.items.length,
              itemBuilder: (BuildContext context, int index) {
                return Container(
                  alignment: Alignment.centerLeft,
                  child: Column(
                    children: <Widget>[
                      _isShowHeader(index),
                      Offstage(
                          //当offstage为false时 显示
                          offstage: _shouldShowSectionHeader(index),
                          child: widget.sectionBuild(context, index)),
                      Column(
                        children: <Widget>[
                          widget.itemsBuild(context, index),
                        ],
                      )
                    ],
                  ),
                );
              },
            ),
          ),
          //排序字母
          Positioned(
            top: MediaQuery.of(context).size.height * 0.25,
            right: 0.0,
            child: Container(
              alignment: Alignment.center,
              height: MediaQuery.of(context).size.height * 0.5,
              width: 32.0,
              color: _pressColor,
              child: GestureDetector(
                onTapDown: (TapDownDetails t) {
                  setState(() {
                    _pressColor = Colors.grey;
                  });
                },
                onTapUp: (TapUpDetails t) {
                  setState(() {
                    _pressColor = Colors.transparent;
                  });
                },
                onVerticalDragStart: (DragStartDetails details) {
                  //开始垂直滑动
                  setState(() {
                    _pressColor = Colors.grey;
                  });
                },
                onVerticalDragEnd: (DragEndDetails details) {
                  setState(() {
                    _pressColor = Colors.transparent;
                  });
                },
                onVerticalDragUpdate: (DragUpdateDetails details) {
                  //手指垂直滑动时
                  setState(() {});
                },
                child: ListView.builder(
                  controller: ScrollController(),
                  itemCount: siderBarKey.length,
                  itemBuilder: (BuildContext context, int index) {
                    return Container(
                      alignment: Alignment.center,
                      height: 17.0,
                      child: Text(siderBarKey[index]),
                    );
                  },
                ),
              ),
            ),
          )
        ],
      ),
    );
  }

  listScrollTopPosition(int index) {
    for (var i = 0; i < widget.items.length; i++) {
      if (siderBarKey[index] == "*" || siderBarKey[index] == "^") {
        _scrollController.jumpTo(0.0);
        setState(() {});
        return -1;
      } else if (widget.items[i].sectionKey == siderBarKey[index]) {
        return i;
      }
    }
    return -1;
  }
}

abstract class SectionInderxer {
  listScrollTopPosition(int index);
}

const siderBarKey = <String>[
  "*",
  "^",
  "A",
  "B",
  "C",
  "D",
  "E",
  "F",
  "G",
  "H",
  "I",
  "J",
  "K",
  "L",
  "M",
  "N",
  "Z",
];

5.最后把上面3个自定义模块 结合数据源进行组装

import 'package:flutter/material.dart';
import 'package:region/region/region_data.dart';
import 'package:region/region/region_header.dart';
import 'package:region/region/region_item.dart';
import 'package:region/region/region_list.dart';

class Regions extends StatefulWidget {
  @override
  RegionState createState() => new RegionState();
}

class RegionState extends State<Regions> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RegionList(
        items: regionDataSource,
        headerBuild: (BuildContext context, int index) {
          return Container(
            child: RegionHeader(
              title: '宁波',
            ),
          );
        },
        itemsBuild: (BuildContext context, int index) {
          return Container(
            color: Colors.white,
            alignment: Alignment.centerLeft,
            child: RegionItem(item: regionDataSource[index]),
          );
        },
        sectionBuild: (BuildContext context, int index){
          return Container(
            height: 22.0,
            padding: const EdgeInsets.only(left: 14.0),
            color: Colors.grey[100],
            alignment: Alignment.centerLeft,
            child: Text(
              regionDataSource[index].sectionKey,
              style: TextStyle(fontSize: 12.0,color: Colors.black87),
            ),
          );
        },
      ),
    );
  }
}

6.最后显示一下
-main.dart

import 'package:flutter/material.dart';
import 'package:region/loading.dart';
import './app.dart';

void main()=> runApp(MaterialApp(
  debugShowCheckedModeBanner: false,
  title: 'weChat',
  theme: mDefaultTheme,
  routes: <String,WidgetBuilder>{
     "app":(BuildContext context) => new App(),
  },
  home: new LoadingPage(),
));

final ThemeData mDefaultTheme = new ThemeData(
  primaryColor: Color(0xff303030),
  scaffoldBackgroundColor: Color(0xFFebebeb),
  cardColor: Color(0xff393a3f),
);

-loading.dart

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

class LoadingPage extends StatefulWidget {
  @override
  _LoadingState createState() => new _LoadingState();
}

class _LoadingState extends State<LoadingPage> {
  @override
  void initState() {
    super.initState();
    new Future.delayed(Duration(seconds: 1),(){
      Navigator.of(context).pushReplacementNamed("app");
    });
  }

  @override
  Widget build(BuildContext context) {

    return new Container(
      child:Image.asset("images/loading.jpg"),
    );
  }
}

-app.dart

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

class App extends StatefulWidget {
  @override
  MainState createState() => MainState();
}

class MainState extends State<App> {
  _cusAppBar() {
    return AppBar(
      title: Text('定位'),
      actions: <Widget>[
        GestureDetector(
          onTap: () {
            Navigator.pushNamed(context, 'search');
          },
          child: Icon(
            Icons.search,
          ),
        ),
        Padding(
          padding: const EdgeInsets.only(left: 20.0, right: 20.0),
          child: GestureDetector(
            onTap: () async {
              showMenu(
                color: Colors.white,
                context: context,
                position: RelativeRect.fromLTRB(500.0, 86.0, 25.0, 0.0),
                items: <PopupMenuEntry>[
                  new PopupMenuItem<String>(
                      value: 'value01', child: new Text('Item One')),
                  new PopupMenuDivider(height: 1.0),
                  new PopupMenuItem<String>(
                      value: 'value02', child: new Text('Item Two')),
                  new PopupMenuDivider(height: 1.0),
                  new PopupMenuItem<String>(
                      value: 'value03', child: new Text('Item Three')),
                  new PopupMenuDivider(height: 1.0),
                  new PopupMenuItem<String>(
                      value: 'value04', child: new Text('I am Item Four'))
                ],
              );
            },
            child: Icon(Icons.add_circle),
          ),
        )
      ],
      flexibleSpace: Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            colors: [Colors.cyan, Colors.blue, Colors.blueAccent],
          ),
        ),
      ),
    );
  }

  Regions region = new Regions();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: _cusAppBar(),
      body: region,
    );
  }
}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,324评论 6 498
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,356评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,328评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,147评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,160评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,115评论 1 296
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,025评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,867评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,307评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,528评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,688评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,409评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,001评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,657评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,811评论 1 268
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,685评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,573评论 2 353

推荐阅读更多精彩内容