Flutter中使用Slider滑块结合map方法实现价格筛选商品列表
Flutter 滑块价格筛选功能实现

需求规则
- 拖动Slider滑块时,页面仅展示价格低于当前滑块取值的商品
- 示例逻辑:滑块取值为20000时,仅展示价格在20000以下的商品
- 必须使用Flutter的
map方法实现筛选逻辑
原有代码错误点
- 商品价格存储为字符串类型,直接与数值类型的滑块值比较会触发类型不匹配错误
- 滑块拖动逻辑错误:每次触发都把全量商品列表追加到展示数组,既没有做价格过滤,还会导致商品列表重复累加、越拖越长
- 商品渲染逻辑错误:遍历数组时用自增的全局索引
i取值,没有读取当前遍历元素的属性,会出现索引越界、商品显示错乱的问题 - 定义了无实际作用的计数变量
i和展示列表a,徒增逻辑复杂度
修正后可运行代码
import 'package:flutter/material.dart'; void main() { runApp( MaterialApp( debugShowCheckedModeBanner: false, home: MyApp(), ), ); } class MyApp extends StatefulWidget { MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { double _value = 0; List product = [ {'id': '1', 'name': 'Watch', 'price': '3200', 'category': 'wearable'}, {'id': '2', 'name': 'T-Shirt', 'price': '520', 'category': 'wearable'}, {'id': '3', 'name': 'Jeans', 'price': '840', 'category': 'wearable'}, { 'id': '4', 'name': 'refrigerator', 'price': '1800', 'category': 'Home Appliance' }, ]; @override Widget build(BuildContext context) { double w = MediaQuery.of(context).size.width; return Scaffold( resizeToAvoidBottomInset: false, appBar: AppBar( title: const Text( "Products Filter", style: TextStyle( color: Colors.white, ), ), centerTitle: true, backgroundColor: Colors.blue, ), body: SingleChildScrollView( child: Column( children: [ Slider( min: 0, max: 80000, onChanged: (double value) { setState(() { _value = value; }); }, value: _value, ), Text( "All Products < Rs. ${_value.toInt()}", style: const TextStyle(fontSize: 18, fontWeight: FontWeight.bold), ), const Padding(padding: EdgeInsets.only(bottom: 20)), Column( children: product.map((e) { // 字符串价格转整数用于数值比较 int productPrice = int.parse(e['price']); // 价格大于等于当前滑块值时,返回空占位组件实现过滤 if (productPrice >= _value) { return const SizedBox.shrink(); } // 符合价格条件的商品渲染卡片 return Container( height: 80, width: w, margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 6), decoration: BoxDecoration( color: Colors.white, borderRadius: BorderRadius.circular(10), boxShadow: [ BoxShadow( color: Colors.grey.shade200, blurRadius: 6, offset: const Offset(0, 2) ) ] ), child: Row( children: [ Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [Text(e['id'])], ), ), Expanded( flex: 2, child: Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: [ Text(e['name'], style: const TextStyle(fontWeight: FontWeight.w500)), Text(e['category'], style: TextStyle(fontSize: 12, color: Colors.grey.shade600)) ], ), ), Expanded( flex: 1, child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ Text("Rs.${e['price']}", style: const TextStyle(color: Colors.blue, fontWeight: FontWeight.bold)), ], ), ) ], ), ); }).toList(), ), ], ), ), ); } }
内容的提问来源于stack exchange,提问作者Akashptl
相关产品推荐
相关产品推荐

