IT数码 购物 网址 头条 软件 日历 阅读 图书馆
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
图片批量下载器
↓批量下载图片,美女图库↓
图片自动播放器
↓图片自动播放器↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁
 
   -> 移动开发 -> Flutter之商城实战分解(上) -> 正文阅读

[移动开发]Flutter之商城实战分解(上)

Flutter之商城实战(上)

一、fluro路由搭建
  • 知识点1

initialRoute:是项目的根路由,初始化的时候最先展示的页面
onGenerateRoute(RouteFactory类型函数):路由钩子,可以对某些指定的路由进行拦截,有时候不想改变页面结构,但是又想要求跳转到这个页面的时候可以用到,比如,页面设定了传参你进行跳转的候。
onUnknownRoute(RouteFactory类型函数):在路由匹配不到的时候用到,一般都返回一个统一的错误页面或404页面
在这里插入图片描述

配置yaml文件

   #路由导航
  fluro: 1.7.8

第一步:

在lib文件下新建一个文件夹Router,下面创建一个文件application.dart
application.dart

//router/application.dart文件
import 'package:fluro/fluro.dart';

//此类主要用于存放Router对象
class Application {
  //Router对象
  static FluroRouter router;
}

Fluro源文件实例化
在这里插入图片描述第二步:
Router,下面创建一个文件routers.dart

//router/routers.dart
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart' hide Router;
import 'package:myshop_flutter/router/router_handlers.dart';
class Routers {
  //根路径,打开启动屏页面
  static String root = "/";
  //主页路径
  static String home = "/home";
  //分类商品页面路径
  static String categoryGoodsList = "/categoryGoodsList";
  //商品详情页面路径
  static String goodsDetail = "/goodsDetail";
  //登录页面路径
  static String login = "/login";
  //注册页面路径
  static String register = "/register";
  //填写订单页面路径
  static String fillInOrder = "/fillInOrder";
  //地址页面路径
  static String address = "/myAddress";
  //地址编辑页面路径
  static String addressEdit = "/addressEdit";
  //我的收藏页面路径
  static String mineCollect = "/mineCollect";
  //关于我们页面路径
  static String aboutUs = "/aboutUs";
  //我的订单页面路径
  static String mineOrder = "/mineOrder";
  //我的订单详情页面路径
  static String mineOrderDetail = "/mineOrderDetail";
  //网页加载路径
  static String webView = "/webView";
  //轮播图路径
  static String brandDetail = "/brandDetail";

  //配置路由
  static void configureRoutes(FluroRouter  router) {

    //找不到路径对应Handler
    router.notFoundHandler = Handler(handlerFunc:
        (BuildContext context, Map<String, List<String>> parameters) {
      print("handler not find");
    });


    //定义路径对应的Handler
    router.define(root, handler: loadingHandler);
    router.define(home, handler: homeHandler);
     router.define(categoryGoodsList, handler: categoryGoodsListHandler);
     router.define(login, handler: loginHandler);
     router.define(register, handler: registerHandler);
     router.define(goodsDetail, handler: goodsDetailsHandler);
     router.define(fillInOrder, handler: fillInOrderHandler);
     router.define(address, handler: addressHandler);
     router.define(addressEdit, handler: addressEditHandler);
    // router.define(mineCollect, handler: collectHandler);
     router.define(aboutUs, handler: aboutHandler);
     router.define(mineOrder, handler: orderHandler);
    // router.define(mineOrderDetail, handler: orderDetailHandler);
    // router.define(webView, handler: webViewHandler);
  }
}

创建router_handlers.dart

//router/router_handlers.dart文件
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:myshop_flutter/page/CategoryPage/GoodCategory/goods_category_page.dart';
import 'package:myshop_flutter/page/CategoryPage/GoodCategory/goods_detail_page.dart';
import 'package:myshop_flutter/page/Mine/AddressEditPage.dart';
import 'package:myshop_flutter/page/Mine/AddressPage.dart';
import 'package:myshop_flutter/page/Mine/about_us_page.dart';
import 'package:myshop_flutter/page/home/index_page.dart';
import 'package:myshop_flutter/page/loading/loading_page.dart';
import 'package:myshop_flutter/page/order/FillInOrderPage.dart';
import 'package:myshop_flutter/page/order/OrderPage.dart';
import 'package:myshop_flutter/page/user/LoginPage.dart';
import 'package:myshop_flutter/page/user/RegisterPage.dart';
import 'package:myshop_flutter/utils/string_util.dart';
//首页
var homeHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return const HomeIndexPage();});

//登录页
var loginHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return const LoginPage();
});

//加载页
var loadingHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return LoadingPage();
});
//注册
var registerHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return RegisterPage();
});
//商品列表
var categoryGoodsListHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<Object>> parameters) {
  //分类名称
  var cateforyName = StringUtil.decode(parameters["categoryName"].first).toString();
  print("cateforyName" + cateforyName);
  print("categoryId" + parameters["categoryId"].first);
  //分类Id
  var categoryId = int.parse(parameters["categoryId"].first);
  return GoodsCategoryPage(categoryName: cateforyName, categoryId: categoryId);
});
//商品详情
var goodsDetailsHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<Object>> parameters) {
  //商品Id
  var goodsId = int.parse(parameters["goodsId"].first);
  return GoodsDetailPage(goodsId: goodsId);
});
//订单
var orderHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return OrderPage();
});
//填写订单
var fillInOrderHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  //购物车Id
  var cartId = int.parse(parameters["cartId"].first);
  return FillInOrderPage(cartId);
});
//关于我们
var aboutHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return AboutUsPage();
});
//地址
var addressHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  return AddressPage();
});

//地址修改
var addressEditHandler = Handler(handlerFunc: (BuildContext context, Map<String, List<String>> parameters) {
  //地址Id
  var addressId = int.parse(parameters["addressId"].first);
  return AddressEditPage(addressId);
});

main.dart

import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:myshop_flutter/router/application.dart';
import 'package:myshop_flutter/router/routers.dart';

void main() {
  //初始化时把配置的路由加入到实例化对象中
  final router = FluroRouter();
  Routers.configureRoutes(router);
  Application.router = router;
  runApp(const MyApp());
}

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      onGenerateRoute: Application.router.generator,
     theme: ThemeData(
       textTheme: TextTheme(
         bodyText1: TextStyle(color: Colors.red,fontSize: 24)
       )
     ),
    );
  }
}

在这里插入图片描述配置根路由

二、配置需要的颜色、样式、图标、标题、api

新建config文件
在这里插入图片描述

color.dart

//config/color.dart文件
import 'dart:ui';
import 'package:flutter/material.dart';
//主要颜色常量
class KColor{
  static const Color primaryColor = Colors.red;//默认主要颜色
  static const Color defaultTextColor = Colors.redAccent;//默认文本颜色
  static const Color defaultButtonColor = Colors.redAccent;//默认按钮颜色
  static const Color defaultSwitchColor = Colors.redAccent;//默认切换按钮颜色
  static const Color defaultCheckBoxColor = Colors.redAccent;//默认复选框按钮颜色
  static const Color toastBgColor = Colors.redAccent;//Toast提示背景颜色
  static const Color watingColor = Colors.redAccent;//加载数据提示颜色
  static const Color toastTextColor = Colors.white;//Toast提示文本颜色
  static const Color priceColor = Colors.redAccent;//价格颜色
  static const Color indexTabSelectedColor = Colors.red;//选项卡按钮选中颜色
  static const Color indexTabUnSelectedColor = Colors.grey;//选项卡按钮未选中颜色
  static const Color bannerDefaultColor = Colors.white;//轮播图激活小点默认颜色
  static const Color bannerActiveColor = Colors.red;//轮播图激活小点选中颜色
  static const Color categorySelectedColor = Colors.redAccent;//分类选中颜色
  static const Color categoryDefaultColor = Colors.black54;//分类默认中颜色
  static const Color noDataTextColor = Colors.redAccent;//没有数据文本颜色
  static const Color loginButtonColor = Colors.redAccent;//登录按钮颜色
  static const Color loginIconColor = Colors.redAccent;//登录图标颜色
  static const Color registerTextColor = Colors.redAccent;//马上注册文本颜色
  static const Color registerButtonColor = Colors.redAccent;//注册按钮颜色
  static const Color registerIconColor = Colors.redAccent;//注册图标颜色
  static const Color collectionButtonColor = Colors.redAccent;//收藏按钮颜色
  static const Color unCollectionButtonColor = Colors.grey;//取消收藏按钮颜色
  static const Color addCartIconColor = Colors.redAccent;//购物车图标颜色
  static const Color addCartButtonColor = Colors.green;//添加至购物车按钮颜色
  static const Color buyButtonColor = Colors.red;//立即购买按钮颜色
  static const Color attributeTextColor = Colors.black54;//商品属性文本颜色
  static const Color issueQuestionColor = Colors.black54;//常见问题颜色
  static const Color issueAnswerColor = Colors.grey;//常见问题回答颜色
  static const Color specificationWarpColor = Colors.redAccent;//商品规格选中颜色
}

icon.dart

//config/icon.dart文件
import 'package:flutter/widgets.dart';
//图标常量
class KIcon{
  static const String FONT_FAMILY = 'ShopICon';//字体名称
  static const IconData PASS_WORD = const IconData(0xe617, fontFamily: KIcon.FONT_FAMILY);//密码图标
  static const IconData ADDRESS=const IconData(0xe63c,fontFamily: KIcon.FONT_FAMILY);//地址图标
  static const IconData ORDER=const IconData(0xe634,fontFamily: KIcon.FONT_FAMILY);//订单图标
  static const IconData COLLECTION=const IconData(0xe61e,fontFamily: KIcon.FONT_FAMILY);//收藏图标
  static const IconData ABOUT_US=const IconData(0xe654,fontFamily: KIcon.FONT_FAMILY);//关于我们图标
}

string.dart

//config/string.dart文件
//字符串常量
class KString {
  static const String NO_DATA_TEXT = "暂无数据";
  static const String NEW_PRODUCT = "新品";
  static const String HOT_PRODUCT = "热卖产品";
  static const String HOME = "首页";
  static const String CATEGORY = "分类";
  static const String SHOP_CAR = "购物车";
  static const String MINE = "我的";
  static const String SERVER_EXCEPTION = "请求网络数据异常";
  static const String GOODS_DETAIL = "商品详情";
  static const String GOODS_ATTRIBUTES = "商品属性";
  static const String COMMON_PROBLEM = "常见问题";
  static const String ADD_CART = "加入购物车";
  static const String BUY = "立即购买";
  static const String LOGIN = "登录";
  static const String REGISTER = "注册";
  static const String ACCOUNT_HINT = "请输入手机号码";
  static const String PASSWORD_HINT = "请输入密码";
  static const String ACCOUNT = "账号";
  static const String PASSWORD = "密码";
  static const String ACCOUNT_RULE = "账号必须为长度为11的数字";
  static const String PASSWORD_RULE = "密码最少为6位";
  static const String NOW_REGISTER = "马上注册";
  static const String NICK_NAME = "NICK_NAME";
  static const String HEAD_URL = "HEAD_URL";
  static const String REGISTER_SUCCESS = "注册成功";
  static const String PRICE = "价格";
  static const String ALREAD_SELECTED = "已选择";
  static const String SPECIFICATIONS = "规格";
  static const String NUMBER = "数量";
  static const String ISLOGIN = "isLogin";
  static const String NICKNAME = "nickName";
  static const String AVATARURL = "avatarUrl";
  static const String LOGIN_SUCESS = "登录成功";
  static const String SUCCESS = "success";
  static const String ADD_CART_SUCCESS = "添加成功";
  static const String CART = "购物车";
  static const String TOTAL_MONEY = "共计";
  static const String EDIT = "编辑";
  static const String COMPLETE = "完成";
  static const String DELETE = "删除";
  static const String BUY_NOW = "下单";
  static const String ORDER = "我的订单";
  static const String ADDRESS = "地址管理";
  static const String COLLECTION = "收藏";
  static const String ABOUT_US = "关于我们";
  static const String CLICK_LOGIN = "点击登录";
  static const String SETTLEMENT = "结算";
  static const String TIPS = "提示";
  static const String DELETE_CART_ITEM_TIPS = "是否确认删除?";
  static const String CONFIRM = "确认";
  static const String CANCEL = "取消";
  static const String DELETE_SUCCESS = "删除成功";
  static const String FILL_IN_ORDER = "填写订单";
  static const String DEFAULT = "默认";
  static const String REMARK = "备注";
  static const String GOODS_TOTAL = "商品合计";
  static const String FREIGHT = "运费";
  static const String PAY = "付款";
  static const String MY_ADDRESS = "我的收货地址";
  static const String ADD_ADDRESS = "添加新地址";
  static const String IS_DEFAULT = "默认";
  static const String ADDRESS_EDIT = "编辑";
  static const String ADDRESS_EDIT_TITLE = "编辑地址";
  static const String ADDRESS_PLEASE_INPUT_NAME = "请输入联系人姓名";
  static const String ADDRESS_PLEASE_INPUT_PHONE = "请输入联系人电话";
  static const String ADDRESS_PLEASE_SELECT_CITY = "请选择地址";
  static const String ADDRESS_PLEASE_INPUT_DETAIL = "请输入详细地址如街道、楼栋房号等";
  static const String ADDRESS_SET_DEFAULT = "设为默认地址";
  static const String ADDRESS_DELETE = "删除收货地址";
  static const String SUBMIT = "提交";
  static const String SUBMIT_SUCCESS = "提交成功";
  static const String ADDRESS_DELETE_SUCCESS = "删除成功";
  static const String PLEASE_SELECT_ADDRESS = "请选择收货地址";
  static const String MINE_COLLECT = "我的收藏";
  static const String MINE_CANCEL_COLLECT = "是否确定取消收藏此商品?";
  static const String MINE_ABOUT_US = "关于我们";
  static const String MINE_ABOUT_US_CONTENT = "FlutterShop";
  static const String MINE_ABOUT_NAME_TITLE = "公司名称";
  static const String MINE_ABOUT_NAME = "Flutter";
  static const String MINE_ABOUT_EMAIL_TITLE = "邮箱";
  static const String MINE_ABOUT_EMAIL = "flutter@gmail.com";
  static const String MINE_ABOUT_TEL_TITLE = "联系电话";
  static const String MINE_ABOUT_TEL = "400-100-100";
  static const String MINE_ORDER = "我的订单";
  static const String HOME_TITLE = "首页";
  static const String CATEGORY_TITLE = "分类";
  static const String MINE_ORDER_TOTAL_GOODS = "共计";
  static const String MINE_ORDER_GOODS_TOTAL = "件商品,";
  static const String MINE_ORDER_PRICE = "合计¥";
  static const String MINE_ORDER_SN = "订单编号:";
  static const String MINE_ORDER_DETAIL = "订单详情";
  static const String MINE_ORDER_TIME = "订单时间";
  static const String ORDER_INFORMATION = "商品信息";
  static const String DOLLAR = "¥";
  static const String MINE_ORDER_DETAIL_TOTAL = "商品合计";
  static const String MINE_ORDER_DETAIL_PAYMENTS = "实付";
  static const String MINE_ORDER_DELETE_SUCCESS = "删除成功";
  static const String MINE_ORDER_CANCEL_SUCCESS = "取消成功";
  static const String MINE_ORDER_DELETE_TIPS = "是否确认删除此订单";
  static const String MINE_ORDER_CANCEL_TIPS = "是否确认取消此订单";
  static const String MINE_ORDER_ALREADY_CANCEL = "已取消";
  static const String PLEASE_LOGIN = "请先登录";
  static const String LOADING = "正在加载中...";
  static const String TOKEN = "X-Shop-Token";
  static const String LOGIN_OUT = "退出登录";
  static const String LOGIN_OUT_TIPS="是否确认退出当前账号";
  static const String ORDER_TITLE = "订单";
}

server_url.dart

//config/server_url.dart文件
//服务端接口地址
class ServerUrl {
  static const String BASE_URL = 'http://172.18.1.64:8080/client';//基础地址

  static const String HOME_URL = BASE_URL+'/home/index';//首页数据

  static const String CATEGORY_FIRST = BASE_URL+'/catalog/getfirstcategory';//商品分类第一级
  static const String CATEGORY_SECOND = BASE_URL+'/catalog/getsecondcategory';//商品分类第二级

  static const String GOODS_CATEGORY = BASE_URL+"/goods/category";//获取商品分类数据
  static const String GOODS_LIST = BASE_URL+'/goods/list';//获取商品数据列表
  static const String GOODS_DETAILS_URL = BASE_URL+'/goods/detail';//商品详情

  static const String REGISTER = BASE_URL+'/auth/register';//注册
  static const String LOGIN = BASE_URL+'/auth/login';//登录
  static const String LOGIN_OUT = BASE_URL+"/auth/logout";//退出登录

  static const String CART_ADD = BASE_URL+'/cart/add';//加入购物车
  static const String CART_LIST = BASE_URL+'/cart/index';//购物车数据
  static const String CART_UPDATE = BASE_URL+'/cart/update';//更新购物车
  static const String CART_DELETE = BASE_URL+'/cart/delete';//删除购物车数据
  static const String CART_CHECK = BASE_URL+'/cart/checked';//购物车商品勾选
  static const String CART_BUY = BASE_URL+'/cart/checkout';//购物车下单
  static const String FAST_BUY = BASE_URL+'/cart/fastadd';//立即购买

  static const String ADDRESS_LIST = BASE_URL+'/address/list';//地址列表
  static const String ADDRESS_SAVE = BASE_URL+'/address/save';//增加地址
  static const String ADDRESS_DELETE = BASE_URL+'/address/delete';//删除地址
  static const String ADDRESS_DETAIL = BASE_URL+'/address/detail';//地址详情

  static const String COLLECT_LIST = BASE_URL+ '/collect/list'; //收藏列表
  static const String COLLECT_ADD_DELETE = BASE_URL+ '/collect/addordelete'; //添加或取消收藏

  static const String ORDER_SUBMIT = BASE_URL+ '/order/submit';// 提交订单
  static const String ORDER_LIST = BASE_URL+'/order/list';//我的订单
  static const String ORDER_DETAIL = BASE_URL+"/order/detail";//订单详情
  static const String ORDER_CANCEL = BASE_URL+"/order/cancel";//取消订单
  static const String ORDER_DELETE = BASE_URL+"/order/delete";//取消订单

}

index.dart

//config/index.dart文件
//导出配置
export 'color.dart';//导出颜色配置
export 'icon.dart';//导出图标配置
export 'string.dart';//导出字符串配置
export 'server_url.dart';//导出后端接口地址配置
三、配置工具类

在这里插入图片描述
新建utils
string_util.dart

//utils/string_util.dart文件
import 'dart:convert';
//字符串处理工具
class StringUtil {
  //字符串json编码
  static String encode(String originalCn) {
    return jsonEncode(Utf8Encoder().convert(originalCn));
  }
  //字符串json解码
  static String decode(String encodeCn) {
    var list = List<int>();
    jsonDecode(encodeCn).forEach(list.add);
    String value = Utf8Decoder().convert(list);
    return value;
  }
}

fluro_convert_util.dart

//utils/fluro_convert_util.dart文件
import 'dart:convert';
//Fluro参数处理工具
class FluroConvertUtil{
  //Object转为String Json
  static String objectToString<T>(T t) {
    return fluroCnParamsEncode(jsonEncode(t));
  }
  //String Json转为Map
  static Map<String, dynamic> stringToMap(String str) {
    return json.decode(fluroCnParamsDecode(str));
  }
  //Fluro传递中文参数前先转换,Fluro不支持中文传递
  static String fluroCnParamsEncode(String originalCn) {
    return jsonEncode(Utf8Encoder().convert(originalCn));
  }
  //Fluro传递后取出参数解析
  static String fluroCnParamsDecode(String encodeCn) {
    var list = List<int>();
    jsonDecode(encodeCn).forEach(list.add);
    String value = Utf8Decoder().convert(list);
    return value;
  }
}

navigatr_util.dart

//utils/navigatr_util.dart文件
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:myshop_flutter/router/application.dart';
import 'package:myshop_flutter/router/routers.dart';
import 'package:myshop_flutter/utils/fluro_convert_util.dart';
import 'package:myshop_flutter/utils/string_util.dart';

//导航工具提供静态方法简化路由处理代码
class NavigatorUtil {
  //跳转至首页
  static goShopMainPage(BuildContext context) {
    Application.router.navigateTo(
        context,
        Routers.home,
        transition: TransitionType.inFromRight, replace: true);
  }
  //跳转至商品列表页面
  static goCategoryGoodsListPage(BuildContext context, String categoryName, int categoryId) {
    //Json编码处理
    var categoryNameText = StringUtil.encode(categoryName);
    //传递参数为分类Id及分类名称
    Application.router.navigateTo(
        context,
        Routers.categoryGoodsList + "?categoryName=$categoryNameText&categoryId=$categoryId",
        transition: TransitionType.inFromRight);
  }
  //跳转至注册页面
  static goRegister(BuildContext context) {
    Application.router.navigateTo(context, Routers.register,
        transition: TransitionType.inFromRight);
  }
  //跳转至登录页面
  static goLogin(BuildContext context) {
    Application.router.navigateTo(context, Routers.login,
        transition: TransitionType.inFromRight);
  }
  //跳转至商品详情页面
  static goGoodsDetails(BuildContext context, int goodsId) {
    //传递参数为商品Id
    Application.router.navigateTo(
        context, Routers.goodsDetail + "?goodsId=$goodsId",
        transition: TransitionType.inFromRight);
  }
  //返回注册页面
  static popRegister(BuildContext context) {
    Application.router.pop(context);
  }
  //跳转至填写订单页面
  static goFillInOrder(BuildContext context,int cartId) {
    //参数为购物车Id
    Application.router.navigateTo(
        context,
        Routers.fillInOrder+"?cartId=$cartId",
        transition: TransitionType.inFromRight);
  }
  //跳转至地址页面
  static Future goAddress(BuildContext context) {
    return Application.router.navigateTo(context, Routers.address,
        transition: TransitionType.inFromRight);
  }

  //跳转至地址编辑页面
  static Future goAddressEdit(BuildContext context, int addressId) {
    //参数为地址Id
    return Application.router.navigateTo(
        context,
        Routers.addressEdit + "?addressId=$addressId",
        transition: TransitionType.inFromRight);
  }
  //跳转至收藏页面
  static goCollect(BuildContext context) {
    Application.router.navigateTo(context, Routers.mineCollect,
        transition: TransitionType.inFromRight);
  }
  //跳转至关于我们页面
  static goAboutUs(BuildContext context) {
    Application.router.navigateTo(context, Routers.aboutUs,
        transition: TransitionType.inFromRight);
  }
  //跳转至订单页面
  static goOrder(BuildContext context) {
    Application.router.navigateTo(context, Routers.mineOrder,
        transition: TransitionType.inFromRight);
  }
  //跳转至订单详情页面
  static Future goOrderDetail(BuildContext context, int orderId, String token) {
    //参数有订单Id及token
    return Application.router.navigateTo(
        context, Routers.mineOrderDetail + "?orderId=$orderId&token=$token",
        transition: TransitionType.inFromRight);
  }
  //跳转至网页页面
  static goWebView(BuildContext context, String title, String url) {
    //中文参数处理
    var titleName = FluroConvertUtil.fluroCnParamsEncode(title);
    var urlEncode = FluroConvertUtil.fluroCnParamsEncode(url);
    Application.router.navigateTo(
        context, Routers.webView + "?title=$titleName&&url=$urlEncode",
        transition: TransitionType.inFromRight);
  }
  //跳转至轮播图详情页面
  static goBrandDetail(BuildContext context, String titleName, int id) {
    var title = FluroConvertUtil.fluroCnParamsEncode(titleName);
    Application.router.navigateTo(
        context, Routers.brandDetail + "?titleName=$title&id=$id",
        transition: TransitionType.inFromRight);
  }
}

在yaml文件添加

   #网络请求
  dio: ^4.0.0

http_util.dart

//utils/http_util.dart文件
import 'package:dio/dio.dart';
import 'package:myshop_flutter/config/index.dart';
import 'package:myshop_flutter/utils/shared_preferences_util.dart';

//定义dio变量
var dio;
//Http请求处理工具,提供了Get及Post请求封装方法
class HttpUtil {
  //获取HttpUtil实例
  static HttpUtil get instance => _getInstance();
  //定义HttpUtil实例
  static HttpUtil _httpUtil;
  //获取HttpUtil实例方法,工厂模式
  static HttpUtil _getInstance() {
    if (_httpUtil == null) {
      _httpUtil = HttpUtil();
    }
    return _httpUtil;
  }
  //构造方法
  HttpUtil() {
    //选项
    BaseOptions options = BaseOptions(
      //连接超时
      connectTimeout: 5000,
      //接收超时
      receiveTimeout: 5000,
    );
    //实例化Dio
    dio = Dio(options);
    Dio  tokenInter(){
      dio.interceptors.add(InterceptorsWrapper(onRequest: (RequestOptions options,handel) async {
        print("========================请求数据===================");
        print("url=${options.uri.toString()}");
        print("params=${options.data}");
        //锁住
        dio.lock();
        //获取本地token
        await SharedPreferencesUtil.getToken().then((token) {
          //将token值放入请求头里
          options.headers[KString.TOKEN] = token;
        });
        //解锁
        dio.unlock();
        return options;
      }, onResponse: (Response response,handel) {
        if(response==null){
          print("null");
        }
        print("========================请求数据===================");
        print("code=${response.statusCode}");
        print("response=${response.data}");
      }, onError: (DioError error,w) {
        print("========================请求错误===================");
        print("message =${error.message}");
      }));
    }

  }

  //封装get请求
  Future get(String url, {Map<String, dynamic> parameters, Options options}) async {
    //返回对象
    Response response;
    //判断请求参数并发起get请求
    if (parameters != null && options != null) {
      response = await dio.get(url, queryParameters: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.get(url, queryParameters: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.get(url, options: options);
    } else {
      response = await dio.get(url);
    }
    //返回数据
    return response.data;
  }

  //封装post请求
  Future post(String url, {Map<String, dynamic> parameters, Options options}) async {
    //返回对象
    Response response;
    //判断请求参数并发起post请求
    if (parameters != null && options != null) {
      response = await dio.post(url, data: parameters, options: options);
    } else if (parameters != null && options == null) {
      response = await dio.post(url, data: parameters);
    } else if (parameters == null && options != null) {
      response = await dio.post(url, options: options);
    } else {
      response = await dio.post(url);
    }
    //返回数据
    return response.data;
  }
}

四、ui加载页面

在这里插入图片描述画出根路由页面

//page/loading/loading_page.dart文件
import 'package:flutter/material.dart';
import 'package:myshop_flutter/utils/navigator_util.dart';


//加载页面
class LoadingPage extends StatefulWidget {
  @override
  _LoadingPageState createState() => _LoadingPageState();
}

class _LoadingPageState extends State<LoadingPage> {
  @override
  void initState() {
    super.initState();
    //延迟3秒执行
    Future.delayed(Duration(seconds: 3), () {
      //跳转至应用首页
      NavigatorUtil.goShopMainPage(context);
    }
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        color: Colors.white,
        //添加加载图片即广告图
        child: Image.asset(
          "images/loading.png",
          width: double.infinity,
          height: double.infinity,
          //指定填充模式
          fit: BoxFit.fill,
        ),
      ),
    );
  }
}

在这里插入图片描述

import 'package:flutter/material.dart';
import 'package:myshop_flutter/config/index.dart';
import '../CartPage/CartPage.dart';
import '../CategoryPage/CategoryPage.dart';
import 'package:myshop_flutter/page/home/HomePage.dart';
import '../Mine/MinePage.dart';

/* 索引页面用于切换几个主要页面 */
class HomeIndexPage extends StatefulWidget {
  const HomeIndexPage({Key key}) : super(key: key);

  @override
  _HomeIndexPageState createState() => _HomeIndexPageState();
}

class _HomeIndexPageState extends State<HomeIndexPage> {
  //当前索引值
  int _selectedIndex = 0;
    List<Widget> _list = List();
  //主要页面列表
    
  @override
  void initState() {
    super.initState();  
    _list
      ..add(HomePage())
      ..add(CategoryPage())
      ..add(CartPage())
      ..add(MinePage());
  }

  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //页面根据索引进行切换
      body: IndexedStack(
        //当前索引
        index: _selectedIndex,
        //绑定页面
        children: _list,
      ),
      bottomNavigationBar: BottomNavigationBar(
        type: BottomNavigationBarType.fixed,
        selectedItemColor: KColor.indexTabSelectedColor,
        //未选中项的颜色
        unselectedItemColor: KColor.indexTabUnSelectedColor,
        currentIndex: _selectedIndex,
        onTap: _onItemTapped,
        items: const <BottomNavigationBarItem>[
          //首页
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            title: Text(KString.HOME),
          ),
          //分类
          BottomNavigationBarItem(
            icon: Icon(Icons.category),
            title: Text(KString.CATEGORY),
          ),
          //购物车
          BottomNavigationBarItem(
            icon: Icon(Icons.shopping_cart),
            title: Text(KString.SHOP_CAR),
          ),
          //我的
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            title: Text(KString.MINE),
          ),
          //选中项的颜色
        ],
      ),
    );
  }
   _onItemTapped(int index) {
 setState(() {
       this._selectedIndex = index;
  });
  }
}

  移动开发 最新文章
Vue3装载axios和element-ui
android adb cmd
【xcode】Xcode常用快捷键与技巧
Android开发中的线程池使用
Java 和 Android 的 Base64
Android 测试文字编码格式
微信小程序支付
安卓权限记录
知乎之自动养号
【Android Jetpack】DataStore
上一篇文章      下一篇文章      查看所有文章
加:2022-04-01 00:13:15  更:2022-04-01 00:14:20 
 
开发: C++知识库 Java知识库 JavaScript Python PHP知识库 人工智能 区块链 大数据 移动开发 嵌入式 开发工具 数据结构与算法 开发测试 游戏开发 网络协议 系统运维
教程: HTML教程 CSS教程 JavaScript教程 Go语言教程 JQuery教程 VUE教程 VUE3教程 Bootstrap教程 SQL数据库教程 C语言教程 C++教程 Java教程 Python教程 Python3教程 C#教程
数码: 电脑 笔记本 显卡 显示器 固态硬盘 硬盘 耳机 手机 iphone vivo oppo 小米 华为 单反 装机 图拉丁

360图书馆 购物 三丰科技 阅读网 日历 万年历 2024年11日历 -2024/11/24 19:55:31-

图片自动播放器
↓图片自动播放器↓
TxT小说阅读器
↓语音阅读,小说下载,古典文学↓
一键清除垃圾
↓轻轻一点,清除系统垃圾↓
图片批量下载器
↓批量下载图片,美女图库↓
  网站联系: qq:121756557 email:121756557@qq.com  IT数码