Flutter實戰視頻-移動電商-16.補充_保持頁面狀態

16.補充_保持頁面狀態

 

修正一個地方:

設置了item的高度爲380git

橫向列表爲380、最終build的高度也增長了50爲430.json

增長了上面的高度之後,下面那個橫線劃掉的價格能夠顯示出來了。數組

可是仍是有超出的問題。app

 

保持首頁頁面狀態

每次點擊底部的tab標籤。再點擊首頁,首頁的數據就會從新加載。less

這裏就用到了混入,在頁面上進行混入:with AutomaticKeepAliveClientMixinjsp

混入以後必須主要三點:async

第一,添加混入ide

第二:重寫wantKeepAlive方法,返回爲true函數

第三,改造indexPageflex

 

改造indexPage

 

最終body裏面返回的是:IndexedStack

參數1是索引值就是當前的索引

第二個children由於類型是widget類型的數組 因此改造了tabBodies這個List對象爲Widget類型的

改造以後的

 

homePage頁面重寫initState方法 打印出來一句話,來判斷當前的頁面是否加載了數據

 

效果展現

從別的tab切回來,頁面狀態就保持住了

 

最終代碼

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

 

 

import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'home_page.dart';
import 'category_page.dart';
import 'cart_page.dart';
import 'member_page.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class IndexPage extends StatefulWidget {
  @override
  _IndexPageState createState() => _IndexPageState();
}

class _IndexPageState extends State<IndexPage> {
  final List<BottomNavigationBarItem> bottomTabs=[
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.home),//這裏使用IOS風格的
      title: Text('首頁')
    ),
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.search),
      title: Text('分類')
    ),
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.shopping_cart),
      title: Text('購物車')
    ),
    BottomNavigationBarItem(
      icon:Icon(CupertinoIcons.profile_circled),
      title: Text('會員中心')
    ) 
  ];
  final List<Widget> tabBodies=[
    HomePage(),
    CategoryPage(),
    CartPage(),
    MemberPage()
  ];

  int currentIndex=0;//當前索引
  var currentPage;
 @override
  void initState() {
    currentPage=tabBodies[currentIndex];//默認頁面數組內索引值爲0的頁面
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
     ScreenUtil.instance = ScreenUtil(width: 750,height: 1334)..init(context);

    return Scaffold(
      backgroundColor: Color.fromRGBO(244, 245, 245, 1.0),//顏色固定死,比白色稍微灰一點
      bottomNavigationBar: BottomNavigationBar(
        type:BottomNavigationBarType.fixed,
        currentIndex: currentIndex,//當前索引值
        items: bottomTabs,
        onTap: (index){
          setState(() {
           currentIndex=index;
           currentPage=tabBodies[currentIndex];
          });
        },
      ),
      body: IndexedStack(
        index: currentIndex,
        children: tabBodies,
      ),
    );
  }
}
index_page.dart

 

超出邊界的錯誤

I/flutter ( 6079): ══╡ EXCEPTION CAUGHT BY RENDERING LIBRARY ╞═════════════════════════════════════════════════════════
I/flutter ( 6079): The following message was thrown during layout:
I/flutter ( 6079): A RenderFlex overflowed by 2.9 pixels on the bottom.
I/flutter ( 6079):
I/flutter ( 6079): The overflowing RenderFlex has an orientation of Axis.vertical.
I/flutter ( 6079): The edge of the RenderFlex that is overflowing has been marked in the rendering with a yellow and
I/flutter ( 6079): black striped pattern. This is usually caused by the contents being too big for the RenderFlex.
I/flutter ( 6079): Consider applying a flex factor (e.g. using an Expanded widget) to force the children of the
I/flutter ( 6079): RenderFlex to fit within the available space instead of being sized to their natural size.
I/flutter ( 6079): This is considered an error condition because it indicates that there is content that cannot be
I/flutter ( 6079): seen. If the content is legitimately bigger than the available space, consider clipping it with a
I/flutter ( 6079): ClipRect widget before putting it in the flex, or using a scrollable container rather than a Flex,
I/flutter ( 6079): like a ListView.
I/flutter ( 6079): The specific RenderFlex in question is:
I/flutter ( 6079):   RenderFlex#907c5 relayoutBoundary=up17 OVERFLOWING
I/flutter ( 6079):   creator: Column ← ConstrainedBox ← Padding ← Container ← Recommend ← Column ← _SingleChildViewport
I/flutter ( 6079):   ← IgnorePointer-[GlobalKey#ecea8] ← Semantics ← Listener ← _GestureSemantics ←
I/flutter ( 6079):   RawGestureDetector-[LabeledGlobalKey<RawGestureDetectorState>#92ff4] ← ⋯
I/flutter ( 6079):   parentData: <none> (can use size)
I/flutter ( 6079):   constraints: BoxConstraints(0.0<=w<=411.4, h=220.3)
I/flutter ( 6079):   size: Size(411.4, 220.3)
I/flutter ( 6079):   direction: vertical
I/flutter ( 6079):   mainAxisAlignment: start
I/flutter ( 6079):   mainAxisSize: max
I/flutter ( 6079):   crossAxisAlignment: center
I/flutter ( 6079):   verticalDirection: down
I/flutter ( 6079): ◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤◢◤

羣裏面也有遇到這個問題的:先本身解決,不行能夠問問這我的

2019年4月8日-wjw

我覺得是SingleChildScrollView引發的這個問題,因此去掉了這個SingleChildScrollView,仍是用直接Column,發現仍是不行,黃條顯示的更多了。

 

不起做用,恢復原來的代碼:

相關文章
相關標籤/搜索