14 Flutter仿京东商城项目 头部搜索导航布局 修改主题 修正ScreenAdapter类

main.dart

import 'package:flutter/material.dart';
import 'routes/router.dart';
void main() => runApp(MyApp());

class MyApp extends StatefulWidget {
  MyApp({Key key}) : super(key: key);

  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      // home:Tabs() ,
      debugShowCheckedModeBanner: false,
      initialRoute: '/search', 
      onGenerateRoute:onGenerateRoute,
      theme: ThemeData(
        primaryColor: Colors.white
      ),
    );
  }
}

Tabs.dart

import 'package:flutter/material.dart';
import '../../services/ScreenAdaper.dart';

import 'Home.dart';
import 'Cart.dart';
import 'Category.dart';
import 'User.dart';

class Tabs extends StatefulWidget {
  Tabs({Key key}) : super(key: key);

  _TabsState createState() => _TabsState();
}

class _TabsState extends State<Tabs> {
  int _currentIndex = 1;
  PageController _pageController;
  void initState() {
    super.initState();
    this._pageController = new PageController(initialPage: this._currentIndex);
  }

  List<Widget> _pageList = [HomePage(), CategoryPage(), CartPage(), UserPage()];
  @override
  Widget build(BuildContext context) {
    ScreenAdaper.init(context);

    return Container(
      child: Scaffold(
        appBar:_currentIndex!=3?AppBar(
          leading: IconButton(
            icon:
                Icon(Icons.center_focus_weak, size: 28, color: Colors.black87),
            onPressed: null,
          ),
          title:InkWell(
            child: Container(
              height: ScreenAdaper.height(56),
              decoration: BoxDecoration(
                color: Color.fromRGBO(233,233,233, 0.8),
                borderRadius: BorderRadius.circular(30)
              ),
              child: Row(
                crossAxisAlignment: CrossAxisAlignment.center,
                children: <Widget>[
                  Icon(Icons.search),
                  Text('笔记本',style:TextStyle(
                    fontSize: ScreenAdaper.size(28)
                  ))
                ],
              ),
            ),
            onTap: (){
              Navigator.pushNamed(context,'/search');
            },
          ),
          actions: <Widget>[
            IconButton(
              icon: Icon(Icons.message,
                  size: 28, color: Colors.black87),
              onPressed: null,
            )
          ],
        ):AppBar(
          title: Text('用户中心'),
        ),
        //页面状态保持第一种方法:
        //保持所有的页面状态,使用indexedStack
        // body:IndexedStack(
        //   index: this._currentIndex,
        //   children:_pageList
        // ),
        //保持部分页面的状态:
        //

        body: PageView(
          //修改的部分:
          controller: this._pageController,
          children: this._pageList,
          onPageChanged:(index){
            setState(() {
             this._currentIndex=index; 
            });
          },
          // physics: NeverScrollableScrollPhysics(), //禁止pageView滑动
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: this._currentIndex,
          onTap: (index) {
            this.setState(() {
              this._currentIndex = index;
              this._pageController.jumpToPage(this._currentIndex);
            });
          },
          type: BottomNavigationBarType.fixed,
          fixedColor: Colors.red,
          items: [
            BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('首页')),
            BottomNavigationBarItem(
                icon: Icon(Icons.category), title: Text('分类')),
            BottomNavigationBarItem(
                icon: Icon(Icons.shopping_cart), title: Text('购物车')),
            BottomNavigationBarItem(icon: Icon(Icons.people), title: Text('我的'))
          ],
        ),
      ),
    );
  }
}

Home.dart

import 'package:flutter/material.dart';


//热门推荐:
import '../../model/ProductModel.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
// import 'dart:convert';
import '../../services/ScreenAdaper.dart';
import '../../config/Config.dart';
import 'package:dio/dio.dart';
//轮播图类模型:
import '../../model/FocusModel.dart';



class HomePage extends StatefulWidget {
  HomePage({Key key}) : super(key: key);

  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin {
  //轮播图:
  //flutter run -d all 链接多个设备的命令:
  List _focusData = [];
  List _hotProductList=[];
  List _bestProductList=[];
    @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  void initState() {
    super.initState();
    _getFocusData();
    _getHotProductData();
    _getBestProductData();
  }
  //获取轮播图数据:
  _getFocusData() async {
    var api = '${Config.domain}api/focus';
    var result = await Dio().get(api);
    var focusList = FocusModel.fromJson(result.data);
    focusList.result.forEach((value) {
      print(value.title);
      print(value.pic);
    });
    setState(() {
      this._focusData = focusList.result;
    });
  }
  //获取猜你喜欢的数据:
  _getHotProductData() async{
    var api='${Config.domain}api/plist?is_hot=1';
    var result=await Dio().get(api);
    var hotProductList=ProductModel.fromJson(result.data);
    setState(() {
     this._hotProductList= hotProductList.result;
    });
  }
  //获取热门推荐的数据:
  _getBestProductData() async{
    var api='${Config.domain}api/plist?is_best=1';
    var result=await Dio().get(api);
    var bestProductList=ProductModel.fromJson(result.data);
    setState(() {
     this._bestProductList= bestProductList.result;
    });
  }

  Widget _swiperWidget() {
    // List<Map> imgList = [
    //   {"url": "https://www.itying.com/images/flutter/slide01.jpg"},
    //   {"url": "https://www.itying.com/images/flutter/slide02.jpg"},
    //   {"url": "https://www.itying.com/images/flutter/slide03.jpg"}
    // ];
    if (this._focusData.length > 0) {
      return Container(
        child: AspectRatio(
          aspectRatio: 2 / 1,
          child: Swiper(
            itemBuilder: (BuildContext context, int index) {
              String pic=this._focusData[index].pic;
              pic=Config.domain+pic.replaceAll('\\', '/');
              return new Image.network(
                "${pic}",
                fit: BoxFit.fill,
              );
            },
            itemCount: this._focusData.length,
            pagination: new SwiperPagination(),
            control: new SwiperControl(),
            autoplay: true,
          ),
        ),
      );
    } else {
      return Text('加载中~');
    }
  }

  //标题:
  Widget _titleWidget(value) {
    return Container(
      height: ScreenAdaper.height(46),
      margin: EdgeInsets.only(left: ScreenAdaper.width(20)),
      padding: EdgeInsets.only(left: ScreenAdaper.width(20)),
      decoration: BoxDecoration(
          border: Border(
              left: BorderSide(
                  color: Colors.red, width: ScreenAdaper.width(10)))),
      child: Text(value, style: TextStyle(color: Colors.black54)),
    );
  }

  //热门商品:
  Widget _hotProductListWidget() {
    if(this._hotProductList.length>0){
    return Container(
      height: ScreenAdaper.height(240),
      padding: EdgeInsets.all(ScreenAdaper.width(20)),
      // width: double.infinity, //寬度自適應
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemBuilder: (contxt, index) {

          String sPic=this._hotProductList[index].sPic;
          sPic=Config.domain+sPic.replaceAll('\\', '/');
          return Column(
            children: <Widget>[
              Container(
                height: ScreenAdaper.height(140),
                width: ScreenAdaper.width(140),
                margin: EdgeInsets.only(right: ScreenAdaper.width(21)),
                child: Image.network(
                   "${sPic}",
                  fit: BoxFit.cover),
              ),
              Container(
                padding: EdgeInsets.only(top: ScreenAdaper.height(10)),
                height: ScreenAdaper.height(44),
                child: Text(
                  "¥${this._hotProductList[index].price}",
                  style: TextStyle(color: Colors.red),
                  ),
              )
            ],
          );
        },
        itemCount: this._hotProductList.length,
      ),
    );
  
    }else{
      return Text('暂无热门推荐数据');
    }

  }

  Widget _recProductListWidget() {


    var itemWidth = (ScreenAdaper.getScreenWidth() - 30) / 2;
    return         Container(
          padding: EdgeInsets.all(10),
          child: Wrap(
            runSpacing: 10,
            spacing: 10,
            children:this._bestProductList.map((value){
              //图片:
              var sPic=value.sPic;
              sPic=Config.domain+sPic.replaceAll('\\','/');

    return Container(
      padding: EdgeInsets.all(ScreenAdaper.width(20)),
      width: itemWidth,
      decoration:
      BoxDecoration(border: Border.all(color: Colors.black12, width: 1)),
      child: Column(
        children: <Widget>[
          Container(
            width: double.infinity,
            child: AspectRatio(
              aspectRatio: 1 / 1,
              child: Image.network(
                  "${sPic}",
                  fit: BoxFit.cover),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: ScreenAdaper.height(10)),
            child: Text(
              "${value.title}",
              maxLines: 2,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: Colors.black54),
            ),
          ),
          Padding(
            padding: EdgeInsets.only(top: ScreenAdaper.height(20)),
            child: Stack(
              children: <Widget>[
                Align(
                  alignment: Alignment.centerLeft,
                  child: Text(
                    "${value.price}",
                    style: TextStyle(color: Colors.red, fontSize: 16),
                  ),
                ),
                Align(
                  alignment: Alignment.centerRight,
                  child: Text(
                    "¥${value.oldPrice}",
                    style: TextStyle(
                        color: Colors.black54,
                        fontSize: 16,
                        decoration: TextDecoration.lineThrough),
                  ),
                )
              ],
            ),
          )
        ],
      ),
    );
 



            }).toList(),
          ),
        );



  }

  @override
  Widget build(BuildContext context) {
    ScreenAdaper.init(context);
    return ListView(
      children: <Widget>[
        _swiperWidget(),
        SizedBox(height: ScreenAdaper.height(20)),
        _titleWidget("猜你喜欢"),
        _hotProductListWidget(),
        SizedBox(height: ScreenAdaper.height(20)),
        _titleWidget("热门推荐"),
        _recProductListWidget()
      ],
    );
  }
}

ScreenAdaper.dart

import 'package:flutter_screenutil/flutter_screenutil.dart';

class ScreenAdaper {
  //
  static init(context) {
    ScreenUtil.instance = ScreenUtil(width: 750, height: 1334)..init(context);
  }

  static height(double value) {
    return ScreenUtil.getInstance().setHeight(value);
  }

  static width(double value) {
    return ScreenUtil.getInstance().setWidth(value);
  }

  static getScreenHeight() {
    return ScreenUtil.screenHeightDp;
  }

  static getScreenWidth() {
    return ScreenUtil.screenWidthDp;
  }

  static size(double size) { //适配字体
    return ScreenUtil.getInstance().setSp(size);
  }
}
/*  */

Search.dart

import 'package:flutter/material.dart';
import 'package:flutter_jdshop/services/ScreenAdaper.dart';
class SearchPage extends StatefulWidget {
  SearchPage({Key key}) : super(key: key);

  _SearchPageState createState() => _SearchPageState();
}

class _SearchPageState extends State<SearchPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title:Container(
          child: TextField(
            autofocus: true,
            decoration: InputDecoration(
              border: OutlineInputBorder(
                borderRadius: BorderRadius.circular(30),
                borderSide: BorderSide.none
              )
            ),
          ),
          height: ScreenAdaper.height(68),
          decoration: BoxDecoration(
            color: Color.fromRGBO(233,233,233,0.8),
            borderRadius: BorderRadius.circular(30)
          ),
        ),
        actions: <Widget>[
          InkWell(
            child: Container(
              height: ScreenAdaper.height(68),
              width: ScreenAdaper.width(80),
              child: Row(
                children: <Widget>[
                  Text('搜索')
                ],
              ),
            ),
            onTap: (){
              
            },
          )
        ],
      ),
      body: Text('搜索')
    );
  }
}

 

转载于:https://www.cnblogs.com/yiweiyihang/p/11421742.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值