zoukankan      html  css  js  c++  java
  • 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 > 0) {
          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: 100),
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  InkWell(
                    onTap: () {
                      SearchServices.removeHistoryList();
                      this._getHistoryData();
                    },
                    child: Container(
                       ScreenAdaper.width(400),
                      height: ScreenAdaper.height(64),
                      decoration: BoxDecoration(
                          border: Border.all(color: Colors.black54,  1)),
                      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(30),
                          borderSide: BorderSide.none)),
                  onChanged: (value) {
                    this._keywords = value;
                  },
                ),
                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),
                     ScreenAdaper.width(80),
                    child: Row(
                      children: <Widget>[Text('搜索')],
                    ),
                  ),
                  onTap: () {
                    SearchServices.setHistoryData(this._keywords);
                    Navigator.pushReplacementNamed(context, '/productList',
                        arguments: {"keywords": this._keywords});
                  },
                )
              ],
            ),
            body: Container(
              padding: EdgeInsets.all(10),
              child: ListView(
                children: <Widget>[
                  Container(
                    child: Text('热搜', style: Theme.of(context).textTheme.title),
                  ),
                  Divider(),
                  Wrap(
                    children: <Widget>[
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(233, 233, 233, 0.9),
                            borderRadius: BorderRadius.circular(10)),
                        child: Text('女装'),
                      ),
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(233, 233, 233, 0.9),
                            borderRadius: BorderRadius.circular(10)),
                        child: Text('女装'),
                      ),
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(233, 233, 233, 0.9),
                            borderRadius: BorderRadius.circular(10)),
                        child: Text('女装'),
                      ),
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(233, 233, 233, 0.9),
                            borderRadius: BorderRadius.circular(10)),
                        child: Text('女装'),
                      ),
                      Container(
                        padding: EdgeInsets.all(10),
                        margin: EdgeInsets.all(10),
                        decoration: BoxDecoration(
                            color: Color.fromRGBO(233, 233, 233, 0.9),
                            borderRadius: BorderRadius.circular(10)),
                        child: Text('女装'),
                      )
                    ],
                  ),
                  SizedBox(height: 10),
                  //历史记录:
                  _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 > 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,  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)),
          //  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),
                     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)),
           itemWidth,
          decoration:
          BoxDecoration(border: Border.all(color: Colors.black12,  1)),
          child: Column(
            children: <Widget>[
              Container(
                 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()
          ],
        );
      }
    }

  • 相关阅读:
    exchart点击事件,空白无值也能点击触发
    两个界面来回切换展示(左下角 有小demo)
    警告滚动展示
    Oracle高级查询之OVER (PARTITION BY ..)
    解决安装office2007后,原来的*.doc文件的图标变成缩略图
    几个常用的文本处理shell 命令:find、grep、sort、uniq、sed、awk
    CentOS 7.3 安装配置 Nginx
    MySQL5.7.17源码编译安装与配置
    CentOS 7 源码安装 MySQL5.7
    Java命令学习系列(一)——Jps
  • 原文地址:https://www.cnblogs.com/yiweiyihang/p/11450848.html
Copyright © 2011-2022 走看看