16.补充_保持页面状态

Flutter实战视频-移动电商-16.补充_保持页面状态

 

修正一个地方:

设置了item的高度为380

Flutter实战视频-移动电商-16.补充_保持页面状态

横向列表为380、最终build的高度也增加了50为430.

Flutter实战视频-移动电商-16.补充_保持页面状态

增加了上面的高度以后,下面那个横线划掉的价格可以显示出来了。

但是还是有超出的问题。

Flutter实战视频-移动电商-16.补充_保持页面状态

 

保持首页页面状态

每次点击底部的tab标签。再点击首页,首页的数据就会重新加载。

这里就用到了混入,在页面上进行混入:with AutomaticKeepAliveClientMixin

Flutter实战视频-移动电商-16.补充_保持页面状态

混入之后必须主要三点:

第一,添加混入

第二:重写wantKeepAlive方法,返回为true

Flutter实战视频-移动电商-16.补充_保持页面状态

第三,改造indexPage

 

改造indexPage

Flutter实战视频-移动电商-16.补充_保持页面状态

 

Flutter实战视频-移动电商-16.补充_保持页面状态

最终body里面返回的是:IndexedStack

参数1是索引值就是当前的索引

第二个children因为类型是widget类型的数组 所以改造了tabBodies这个List对象为Widget类型的

Flutter实战视频-移动电商-16.补充_保持页面状态

改造之后的

Flutter实战视频-移动电商-16.补充_保持页面状态

 

homePage页面重写initState方法 打印出来一句话,来判断当前的页面是否加载了数据

Flutter实战视频-移动电商-16.补充_保持页面状态

 

效果展示

从别的tab切回来,页面状态就保持住了

Flutter实战视频-移动电商-16.补充_保持页面状态

 

最终代码

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{

  @override
  bool get wantKeepAlive => true;

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

  String homePageContent='正在获取数据';
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('百姓生活+')),
      body: FutureBuilder(
        future: getHomePageContent(),
        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();

            return SingleChildScrollView(
              child: Column(
                children: <Widget>[
                  SwiperDiy(swiperDateList: swiper),
                  TopNavigator(navigatorList:navigatorList ,),
                  AdBanner(adPicture:adPicture),
                  LeaderPhone(leaderImage: leaderImage,leaderPhone: leaderPhone,),
                  Recommend(recommendList:recommendList)
                ],
              ),
            );
          }else{
            return Center(child: Text('加载中....'));
          }
        },
      ),
    );
  }
}
//首页轮播插件
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()
       ],
      ),
    );
  }
}
home_page.dart

相关文章:

  • 2022-12-23
  • 2021-09-11
  • 2021-12-02
  • 2021-06-01
  • 2021-10-25
  • 2021-12-20
  • 2022-02-10
  • 2022-01-21
猜你喜欢
  • 2021-12-17
  • 2021-10-06
  • 2021-11-13
  • 2021-06-27
  • 2021-10-28
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案