17 Flutter仿京东商城项目 保存历史搜索记录 删除历史记录 清空历史记录 长按删除
Storage.dart
import 'package:shared_preferences/shared_preferences.dart';
class Storage{
static Future<void> setString(key,value) async{
SharedPreferences sp=await SharedPreferences.getInstance();
sp.setString(key, value);
} static Future<String> getString(key) async{
SharedPreferences sp=await SharedPreferences.getInstance();
return sp.getString(key);
} static Future<String> remove(key) async{
SharedPreferences sp=await SharedPreferences.getInstance();
sp.remove(key);
} static Future<String> clear(key) async{
SharedPreferences sp=await SharedPreferences.getInstance();
sp.clear();
}
}
SearchServices.dart
import 'dart:convert';
import 'Storage.dart'; class SearchServices {
static setHistoryData(keywords) async {
/**
* 1.获取本地存储里面的数据。(searchList)
* 2.判断本地存储是否有数据
* 2.1如果有数据:
* 1.读取本地存储的数据。
* 2.判断本地存储中有没有当前数据;
* 3.如果有不做操作
* 如果没有当前数据,本地存储的数据和当前数据拼接后重新写入。
* 2.2如果没有数据:
* 直接把当前数据放在数组中写入到本地存储。
*
*
* */
try {
List searchListData = json.decode(await Storage.getString('searchList'));
// print(searchListData);
var hasData = searchListData.any((v) {
return v == keywords;
});
if (!hasData) {
searchListData.add(keywords);
await Storage.setString('searchList', json.encode(searchListData));
}
} catch (e) {
List tempList = new List();
tempList.add(keywords);
await Storage.setString('searchList', json.encode(tempList));
}
} static getHistoryList() async {
try {
List searchListData = json.decode(await Storage.getString('searchList'));
return searchListData;
} catch (e) {
return [];
}
} static removeHistoryList() async {
await Storage.remove('searchList');
}
}
Search.dart
import 'package:flutter/material.dart';
import 'package:flutter_jdshop/services/ScreenAdaper.dart';
import 'package:flutter_jdshop/services/SearchServices.dart'; class SearchPage extends StatefulWidget {
SearchPage({Key key}) : super(key: key); _SearchPageState createState() => _SearchPageState();
} class _SearchPageState extends State<SearchPage> {
var _keywords;
List _historyListData = [];
@override
void initState() {
super.initState();
this._historyListWidget();
} _getHistoryData() async {
var _historyListData = await SearchServices.getHistoryList();
setState(() {
this._historyListData=_historyListData;
});
} Widget _historyListWidget() {
if (_historyListData.length > ) {
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Container(
child: Text('历史记录', style: Theme.of(context).textTheme.title),
),
Divider(),
Column(
children: this._historyListData.map((value) {
return Column(
children: <Widget>[
ListTile(
title: Text('${value}'),
),
Divider()
],
);
}).toList(),
),
SizedBox(height: ),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: () {
SearchServices.removeHistoryList();
this._getHistoryData();
},
child: Container(
width: ScreenAdaper.width(),
height: ScreenAdaper.height(),
decoration: BoxDecoration(
border: Border.all(color: Colors.black54, width: )),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[Icon(Icons.delete), Text('清空历史记录')],
),
),
)
],
)
],
);
} else {
return Text('');
}
} @override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Container(
child: TextField(
autofocus: true,
decoration: InputDecoration(
border: OutlineInputBorder(
borderRadius: BorderRadius.circular(),
borderSide: BorderSide.none)),
onChanged: (value) {
this._keywords = value;
},
),
height: ScreenAdaper.height(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.8),
borderRadius: BorderRadius.circular()),
),
actions: <Widget>[
InkWell(
child: Container(
height: ScreenAdaper.height(),
width: ScreenAdaper.width(),
child: Row(
children: <Widget>[Text('搜索')],
),
),
onTap: () {
SearchServices.setHistoryData(this._keywords);
Navigator.pushReplacementNamed(context, '/productList',
arguments: {"keywords": this._keywords});
},
)
],
),
body: Container(
padding: EdgeInsets.all(),
child: ListView(
children: <Widget>[
Container(
child: Text('热搜', style: Theme.of(context).textTheme.title),
),
Divider(),
Wrap(
children: <Widget>[
Container(
padding: EdgeInsets.all(),
margin: EdgeInsets.all(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.9),
borderRadius: BorderRadius.circular()),
child: Text('女装'),
),
Container(
padding: EdgeInsets.all(),
margin: EdgeInsets.all(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.9),
borderRadius: BorderRadius.circular()),
child: Text('女装'),
),
Container(
padding: EdgeInsets.all(),
margin: EdgeInsets.all(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.9),
borderRadius: BorderRadius.circular()),
child: Text('女装'),
),
Container(
padding: EdgeInsets.all(),
margin: EdgeInsets.all(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.9),
borderRadius: BorderRadius.circular()),
child: Text('女装'),
),
Container(
padding: EdgeInsets.all(),
margin: EdgeInsets.all(),
decoration: BoxDecoration(
color: Color.fromRGBO(, , , 0.9),
borderRadius: BorderRadius.circular()),
child: Text('女装'),
)
],
),
SizedBox(height: ),
//历史记录:
_historyListWidget()
],
),
));
}
}
Home.dart
import 'package:flutter/material.dart';
import '../../services/SearchServices.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(); SearchServices.setHistoryData('aaa');
}
//获取轮播图数据:
_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 > ) {
return Container(
child: AspectRatio(
aspectRatio: / ,
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(),
margin: EdgeInsets.only(left: ScreenAdaper.width()),
padding: EdgeInsets.only(left: ScreenAdaper.width()),
decoration: BoxDecoration(
border: Border(
left: BorderSide(
color: Colors.red, width: ScreenAdaper.width()))),
child: Text(value, style: TextStyle(color: Colors.black54)),
);
} //热门商品:
Widget _hotProductListWidget() {
if(this._hotProductList.length>){
return Container(
height: ScreenAdaper.height(),
padding: EdgeInsets.all(ScreenAdaper.width()),
// 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(),
width: ScreenAdaper.width(),
margin: EdgeInsets.only(right: ScreenAdaper.width()),
child: Image.network(
"${sPic}",
fit: BoxFit.cover),
),
Container(
padding: EdgeInsets.only(top: ScreenAdaper.height()),
height: ScreenAdaper.height(),
child: Text(
"¥${this._hotProductList[index].price}",
style: TextStyle(color: Colors.red),
),
)
],
);
},
itemCount: this._hotProductList.length,
),
); }else{
return Text('暂无热门推荐数据');
} } Widget _recProductListWidget() { var itemWidth = (ScreenAdaper.getScreenWidth() - ) / ;
return Container(
padding: EdgeInsets.all(),
child: Wrap(
runSpacing: ,
spacing: ,
children:this._bestProductList.map((value){
//图片:
var sPic=value.sPic;
sPic=Config.domain+sPic.replaceAll('\\','/'); return Container(
padding: EdgeInsets.all(ScreenAdaper.width()),
width: itemWidth,
decoration:
BoxDecoration(border: Border.all(color: Colors.black12, width: )),
child: Column(
children: <Widget>[
Container(
width: double.infinity,
child: AspectRatio(
aspectRatio: / ,
child: Image.network(
"${sPic}",
fit: BoxFit.cover),
),
),
Padding(
padding: EdgeInsets.only(top: ScreenAdaper.height()),
child: Text(
"${value.title}",
maxLines: ,
overflow: TextOverflow.ellipsis,
style: TextStyle(color: Colors.black54),
),
),
Padding(
padding: EdgeInsets.only(top: ScreenAdaper.height()),
child: Stack(
children: <Widget>[
Align(
alignment: Alignment.centerLeft,
child: Text(
"${value.price}",
style: TextStyle(color: Colors.red, fontSize: ),
),
),
Align(
alignment: Alignment.centerRight,
child: Text(
"¥${value.oldPrice}",
style: TextStyle(
color: Colors.black54,
fontSize: ,
decoration: TextDecoration.lineThrough),
),
)
],
),
)
],
),
); }).toList(),
),
); } @override
Widget build(BuildContext context) {
ScreenAdaper.init(context);
return ListView(
children: <Widget>[
_swiperWidget(),
SizedBox(height: ScreenAdaper.height()),
_titleWidget("猜你喜欢"),
_hotProductListWidget(),
SizedBox(height: ScreenAdaper.height()),
_titleWidget("热门推荐"),
_recProductListWidget()
],
);
}
}
17 Flutter仿京东商城项目 保存历史搜索记录 删除历史记录 清空历史记录 长按删除的更多相关文章
- 01-02 Flutter仿京东商城项目 功能分析、底部导航Tab切换以及路由配置、架构搭建:(Flutter仿京东商城项目 首页布局以及不同终端屏幕适配方案)
Flutter和Dart交流学习群:交流群:452892873 01Flutter仿京东商城项目 功能分析.底部导航Tab切换以及路由配置.架构搭建 02Flutter仿京东商城项目 首页布局以及不同 ...
- 16 Flutter仿京东商城项目 跳转到搜索页面实现搜索功能 以及搜索筛选
ProductList.dart import 'package:flutter/material.dart'; import '../services/ScreenAdaper.dart'; imp ...
- 15 Flutter仿京东商城项目 搜索页面布局
Search.dart import 'package:flutter/material.dart'; import 'package:flutter_jdshop/services/ScreenAd ...
- 36 Flutter仿京东商城项目 用户登录 退出登录 事件广播更新状态
Login.dart import 'dart:convert'; import 'package:dio/dio.dart'; import 'package:flutter/material.da ...
- 07-08 Flutter仿京东商城项目 商品分类页面布局:Flutter仿京东商城项目 商品分类页面数据渲染
Flutter实战(交流群:452892873) 本项目是一个实战项目,根据目录建文件,并复制从第一节到最新更新的文章,可以构成完整的一个请求后台数据的项目: CateModel.dart class ...
- 42 Flutter仿京东商城项目 修改默认收货地址 显示默认收货地址
CheckOut.dart import 'package:flutter/material.dart'; import '../services/ScreenAdapter.dart'; impor ...
- 41 Flutter 仿京东商城项目签名验证 增加收货地址、显示收货地址 事件广播
加群452892873 下载对应41课文件,运行方法,建好项目,直接替换lib目录 AddressAdd.dart import 'package:dio/dio.dart'; import 'pac ...
- 39 Flutter仿京东商城项目 收货地址列表、增加 修改收货地址布局、弹出省市区选择器
加群452892873 下载对应39课文件,运行方法,建好项目,直接替换lib目录 pubspec.yaml city_pickers: ^ AddressAdd.dart import 'packa ...
- 38 Flutter仿京东商城项目 渲染结算页面商品数据
加群452892873 下载对应38课文件,运行方法,建好项目,直接替换lib目录 CartServices.dart import 'dart:convert'; import 'Storage.d ...
随机推荐
- tsp问题-遍历算法/随机算法
旅行商问题,即TSP问题(Traveling Salesman Problem)又译为旅行推销员问题.货郎担问题,是数学领域中著名问题之一.假设有一个旅行商人要拜访n个城市,他必须选择所要走的路径,路 ...
- SP15637 GNYR04H - Mr Youngs Picture Permutations[DP]
题目来源:POJ:http://poj.org/problem?id=2279 SPOJ:https://www.spoj.com/problems/GNYR04H/ 题意翻译 题目描述 杨先生希望为 ...
- java-集合处理数据的效率差异
先给结论,ArrayList数组结构的,插入和删除耗时长,get(index)耗时短. LinkedList是链表结构的,插入和删除耗时短,get(index)耗时长. 常用的几种集合,ArrayLi ...
- linux实操_网络配置
1.ping测试主机之间网络连通性 ping 目的主机 (功能描述:测试当前服务器是否可以连接目的主机) 2.查看网络配置信息 ifconfig 3.linux网络环境配置 第一种(自动获取) 勾选自 ...
- Java集合--Collection
概要 首先,我们对Collection进行说明.下面先看看Collection的一些框架类的关系图: Collection是一个接口,它主要的两个分支是:List 和 Set. List和Set都是接 ...
- python-windows安装相关问题
1.python的环境配置,有些时候是没有配置的,需要在[系统环境]-[path]里添加. 2.安装pip:从官网下载pip包,然后到包目录==>python setup.py install ...
- easyui-filebox上传图片到阿里
应用场景:在fixbox图片上传时在预览图片img标签底下点击按钮触发一下函数 参考:https://www.cnblogs.com/awzf/p/9843814.html js //修改该时上传产品 ...
- TFS命令行
tfs命令工具: https://docs.microsoft.com/en-us/previous-versions/visualstudio/visual-studio-2010/9s5ae285 ...
- 关于npm audit fix
https://blog.csdn.net/weixin_40817115/article/details/81007774 npm audit : npm@5.10.0 & npm@6,允许 ...
- Oracle 11g关闭用户连接审计
sys.aud$表数据量增长较快.这时,不想关闭数据库的审计,但是又不想频繁的清理sys.aud$表.可进行如下操作关闭数据库连接的审计 noaudit connect;