Flutter實戰視頻-移動電商-19.首頁_火爆專區界面佈局編寫

19.首頁_火爆專區界面佈局編寫

看一下圖片的效果json

一個標題欄,下面是多行兩列。裏面能夠用column佈局,外面用Warp流式佈局app

有得小夥伴說這裏能夠用網格佈局,網格佈局的話仍是有必定的效率問題。這裏就用咱們的流佈局,仍是很順暢的less

填一下上節課的坑,設置可選參數

這裏用花括號括起來就是個可先的參數了。jsp

修改爲可選參數後呢,咱們在調用方法的時候就報錯了。async

咱們只要修改成key/value的形式就能夠了ide

上拉刷新有幾種方式函數

火爆專區主要的代碼,這是以前的,如今要刪掉了佈局

//火爆專區 定義爲動態的類
class HotGoods extends StatefulWidget {
  @override
  _HotGoodsState createState() => _HotGoodsState();
}

class _HotGoodsState extends State<HotGoods> {
  void initState() { 
    super.initState();
    request('homePageBelowConten',formData:1).then((val){
      print(val);
    });
  }
  @override
  Widget build(BuildContext context) {
    return Container(
      child:Text('111111')
    );
  }
}

 

咱們在最上面定義兩個變量。使用的是State For Widget的形式測試

定義一個內部的方法去獲取遠程數據,內部方法用下劃線開頭 _getHotGoods()ui

建立火爆專區的標題

 

 

//火爆專區的標題
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top:10.0),//上邊距
    alignment: Alignment.center,//居中對齊
    color: Colors.transparent,
    child: Text('火爆專區'),
  );

 

 

流式佈局

流式佈局的問題,若是數據是空 那麼返回流式佈局就會報錯

因此咱們須要判斷數據的list的長度

把list包裝成Widget

把商品的List<Map>的形式,轉換成了 List<Widget的形式>

 

最終再返回咱們的wrap佈局

 

else的狀況,當列表數據爲空那麼咱們就返回一個空的Text widget

 

把標題和流式佈局組合起來

調用加載數據的方法

 

 

測試效果展現

 

往下拖還有一些數據

 

標題加上內邊距

 

 

邊距稍微好看了點

 

最終代碼

import 'package:flutter/material.dart';
import '../service/service_method.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'dart:convert';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin{

  int page=1;
  List<Map> hotGoodsList=[];
  @override
  bool get wantKeepAlive => true;

  @override
  void initState() { 
    super.initState();
    _getHotGoods();
    print('1111111');
  }

  String homePageContent='正在獲取數據';
  @override
  Widget build(BuildContext context) {
     var formData={'lon':'115.02932','lat':'35.76189'};//傳一個經緯度過去,防止惡意下單
    return Scaffold(
      appBar: AppBar(title: Text('百姓生活+')),
      body: FutureBuilder(
        future: request('homePageContent',formData:formData),
        builder: (context, snapshot) {
          if(snapshot.hasData){
            var data=json.decode(snapshot.data.toString());
            List<Map> swiper=(data['data']['slides'] as List).cast();
            List<Map> navigatorList=(data['data']['category'] as List).cast();
            String adPicture=data['data']['advertesPicture']['PICTURE_ADDRESS'];
            String leaderImage=data['data']['shopInfo']['leaderImage'];
            String leaderPhone=data['data']['shopInfo']['leaderPhone'];
            List<Map> recommendList=(data['data']['recommend'] as List).cast();
            String floor1Title=data['data']['floor1Pic']['PICTURE_ADDRESS'];
            String floor2Title=data['data']['floor2Pic']['PICTURE_ADDRESS'];
            String floor3Title=data['data']['floor3Pic']['PICTURE_ADDRESS'];
            List<Map> floor1=(data['data']['floor1'] as List).cast();
            List<Map> floor2=(data['data']['floor2'] as List).cast();
            List<Map> floor3=(data['data']['floor3'] as List).cast();

            return SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  SwiperDiy(swiperDateList: swiper),
                  TopNavigator(navigatorList:navigatorList ,),
                  AdBanner(adPicture:adPicture),
                  LeaderPhone(leaderImage: leaderImage,leaderPhone: leaderPhone,),
                  Recommend(recommendList:recommendList),
                  FloorTitle(picture_address: floor1Title,),//樓層1的標題圖片
                  FloorContent(floorGoodsList: floor1),
                   FloorTitle(picture_address: floor2Title,),//樓層1的標題圖片
                  FloorContent(floorGoodsList: floor2),
                   FloorTitle(picture_address: floor3Title,),//樓層1的標題圖片
                  FloorContent(floorGoodsList: floor3),
                  _hotGoods()
                ],
              ),
            );
          }else{
            return Center(child: Text('加載中....'));
          }
        },
      ),
    );
  }

  void _getHotGoods(){
    var formData={'page',page};
    request('homePageBelowConten',formData:formData).then((val){
      var data=json.decode(val.toString());
      List<Map> newGoodsList=(data['data'] as List).cast();
      //把新的列表加到老的列表裏面
      setState(() {
        hotGoodsList.addAll(newGoodsList);
        page++;
      });
    });
  }
  //火爆專區的標題
  Widget hotTitle = Container(
    margin: EdgeInsets.only(top:10.0),//上邊距
    alignment: Alignment.center,//居中對齊
    color: Colors.transparent,
    padding: EdgeInsets.all(5.0),
    child: Text('火爆專區'),
  );

  Widget _wrapList(){
    if(hotGoodsList.length!=0){
      List<Widget> listWidget=hotGoodsList.map((val){
        return InkWell(
          onTap: (){},
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),//內邊距
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(val['image'],width: ScreenUtil().setWidth(370),),//設置寬度防止超出邊界
                Text(
                  val['name'],
                  maxLines: 1,//只有一行
                  overflow: TextOverflow.ellipsis,//超出顯示省略號的形式
                  style: TextStyle(color: Colors.pink,fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('¥${val['mallPrice']}'),//商城價格
                    Text(
                      '¥${val['price']}',
                      style: TextStyle(color: Colors.black26,decoration: TextDecoration.lineThrough),//加上刪除線的價格
                    )
                  ],
                )
              ],
            ),
          ),
        );
      }).toList();
      return Wrap(
        spacing:2 ,//每一行顯示兩列
        children: listWidget,
      );
    }else{
      return Text('');
    }
  }

  //組合火爆專區的標題和列表
  Widget _hotGoods(){
    return Container(
      child: Column(
        children: <Widget>[
          hotTitle,
          _wrapList()
        ],
      ),
    );
  }


}
//首頁輪播插件
class SwiperDiy extends StatelessWidget {
  final List swiperDateList;
  //構造函數
  SwiperDiy({this.swiperDateList});

  @override
  Widget build(BuildContext context) {
  
   

    // print('設備的像素密度:${ScreenUtil.pixelRatio}');
    // print('設備的高:${ScreenUtil.screenWidth}');
    // print('設備的寬:${ScreenUtil.screenHeight}');

    return Container(
      height: ScreenUtil().setHeight(333),//
      width:ScreenUtil().setWidth(750),
      child: Swiper(
        itemBuilder: (BuildContext context,int index){
          return Image.network("${swiperDateList[index]['image']}",fit: BoxFit.fill,);
        },
        itemCount: swiperDateList.length,
        pagination: SwiperPagination(),
        autoplay: true,
      ),
    );
  }
}

class TopNavigator extends StatelessWidget {
  final List navigatorList;

  TopNavigator({Key key, this.navigatorList}) : super(key: key);

  Widget _gridViewItemUI(BuildContext context,item){
    return InkWell(
      onTap: (){print('點擊了導航');},
      child: Column(
        children: <Widget>[
          Image.network(item['image'],width: ScreenUtil().setWidth(95)),
          Text(item['mallCategoryName'])
        ],
      ),
    );
  }
  @override
  Widget build(BuildContext context) {
    if(this.navigatorList.length>10){
      this.navigatorList.removeRange(10,this.navigatorList.length);//從第十個截取,後面都截取掉
    }
    return Container(
      height: ScreenUtil().setHeight(320),//只是本身大概預估的一個高度,後續能夠再調整
      padding: EdgeInsets.all(3.0),//爲了避免讓它切着屏幕的邊緣,咱們給它一個padding
      child: GridView.count(
        crossAxisCount: 5,//每行顯示5個元素
        padding: EdgeInsets.all(5.0),//每一項都設置一個padding,這樣他就不挨着了。
        children: navigatorList.map((item){
          return _gridViewItemUI(context,item);
        }).toList(),
      ),
    );
  }
}

class AdBanner extends StatelessWidget {
  final String adPicture;

  AdBanner({Key key, this.adPicture}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Image.network(adPicture),
    );
  }
}

//店長電話模塊
class LeaderPhone extends StatelessWidget {
  final String leaderImage;//店長圖片
  final String leaderPhone;//店長電話 


  LeaderPhone({Key key, this.leaderImage,this.leaderPhone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: _launchURL,
        child: Image.network(leaderImage),
      ),
    );
  }

  void _launchURL() async {
    String url = 'tel:'+leaderPhone;
    //String url = 'http://jspang.com';
    if(await canLaunch(url)){
      await launch(url);
    }else{
      throw 'url不能進行訪問,異常';
    }
  }
}

//商品推薦
class Recommend extends StatelessWidget {
  final List recommendList;

  Recommend({Key key, this.recommendList}) : super(key: key);

  //商品標題
  Widget _titleWidget(){
    return Container(
      alignment: Alignment.centerLeft,//局長靠左對齊
      padding: EdgeInsets.fromLTRB(10.0, 2.0, 0, 5.0),//左上右下
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
          bottom: BorderSide(width: 0.5,color: Colors.black12) //設置底部的bottom的邊框,Black12是淺灰色
        ),
      ),
      child: Text(
        '商品推薦',
        style:TextStyle(color: Colors.pink)
      ),
    );
  }
  //商品單獨項方法
  Widget _item(index){
    return InkWell(
      onTap: (){},//點擊事件先留空
      child: Container(
        height: ScreenUtil().setHeight(380),//兼容性的高度 用了ScreenUtil
        width: ScreenUtil().setWidth(250),//750除以3因此是250
        padding: EdgeInsets.all(8.0),
        decoration: BoxDecoration(
          color: Colors.white,
          border: Border(
            left: BorderSide(width: 1,color: Colors.black12)//右側的 邊線的樣式 寬度和 顏色
          )
        ),
        child: Column(
          children: <Widget>[
            Image.network(recommendList[index]['image']),
            Text('¥${recommendList[index]['mallPrice']}'),
            Text(
              '¥${recommendList[index]['price']}',
              style: TextStyle(
                decoration: TextDecoration.lineThrough,//刪除線的樣式
                color: Colors.grey//淺灰色
              ),
            ),
          ],
        ),
      ),
    );
  }
  //橫向列表方法
  Widget _recommendList(){
    return Container(
      height: ScreenUtil().setHeight(380),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,//橫向的
        itemCount: recommendList.length,
        itemBuilder: (context,index){
          return _item(index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(430),//列表已經設置爲330了由於還有上面標題,因此要比330高,這裏先設置爲380
      margin: EdgeInsets.only(top: 10.0),
      child: Column(
       children: <Widget>[
          _titleWidget(),
          _recommendList()
       ],
      ),
    );
  }
}

//樓層標題
class FloorTitle extends StatelessWidget {
  final String picture_address;

  FloorTitle({Key key, this.picture_address}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: Image.network(picture_address),
    );
  }
}

//樓層商品列表
class FloorContent extends StatelessWidget {
  final List floorGoodsList;

  FloorContent({Key key, this.floorGoodsList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _firstRow(),
          _otherGoods()
        ],
      ),
    );
  }

 Widget _firstRow(){
   return Row(
     children: <Widget>[
       _goodsItem(floorGoodsList[0]),
       Column(
         children: <Widget>[
          _goodsItem(floorGoodsList[1]),
           _goodsItem(floorGoodsList[2])
         ],
       )
     ],
   );
 }
 Widget _otherGoods(){
   return Row(
     children: <Widget>[
        _goodsItem(floorGoodsList[3]),
        _goodsItem(floorGoodsList[4])
     ],
   );
 }
  Widget _goodsItem(Map goods){
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        onTap: (){print('點擊了樓層商品');},
        child: Image.network(goods['image']),
      ),
    );
  }
}
home_page.dart
相關文章
相關標籤/搜索