Flutter开发Feed流笔记二

Flutter开发Feed流笔记二_第1张图片Flutter开发Feed流笔记二_第2张图片

仿照贝壳找房app看点页实现feed流功能。

UI使用了:tabbar+tabbarview+ListView
http通讯:Dio
json:json_serializable
下载刷新/加载更多:flutter_refresh

遇到问题:
1、 tabbarview在切换标签页后, 前一个标签页的状态会丢失。 其实TabbarView也是用的PageView,只需要继承mixin类AutomaticKeepAliveClientMixin并设置wantKeepAlive为true。 原理类似于安卓的ViewPager的pagelimit。

class ContentWidget extends StatefulWidget {
  List dataItems;

  ContentWidget({Key key, this.title, this.dataItems}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _ContentWidgetState createState() => new _ContentWidgetState(dataItems);
}

class _ContentWidgetState extends State with AutomaticKeepAliveClientMixin {
  List dataItems;

  _ContentWidgetState(this.dataItems):super();

  @override
  void dispose() {
    super.dispose();
  }

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return new Scaffold(
      body: Container(
        padding: EdgeInsets.only(left: 24, right: 24, ),
        child: new Refresh(
          onFooterRefresh: onFooterRefresh,
          onHeaderRefresh: onHeaderRefresh,
          childBuilder: (BuildContext context,
              {ScrollController controller, ScrollPhysics physics}) {
            return new Container(
                child: new ListView.builder(
                  physics: physics,
                  controller: controller,
                  itemCount: dataItems.length,
                  itemBuilder: (context, item) {
                    return _getItemWidgetByIndex(item);
                  },
                ));
          },
        ),
      )
    );
  }

  // TODO: implement wantKeepAlive
  @override
  bool get wantKeepAlive => true;

  ///根据下标返回对应的item widget
  Widget _getItemWidgetByIndex(int index) {
    if (dataItems != null && index < dataItems.length) {
      Recommand data = Recommand.fromJson(dataItems[index]);

      //根据类型生成对应的控件widget
      if (data.type == 1) {
        return ThreeImageWidget(currentData: data,);
      } else {
        return RightImageWidget(currentData: data,);
      }
    }
    return ListTile(title: Text('dddd'),);
  }

  // 下拉刷新
  Future onHeaderRefresh() {
    return new Future.delayed(new Duration(seconds: 2), () {

    });
  }

  // 加载刷新
  Future onFooterRefresh() async {
    return new Future.delayed(new Duration(seconds: 2), () {

    });
  }

}

2、 tabbar不支持设置间距, 例如本示例是4个标签, 假如需要标签是横向居中对齐, 暂未发现解决方法;

代码地址: https://github.com/brycegao/FlutterFeed

你可能感兴趣的:(Flutter)