I am trying to display a list of girls who exist within a distance specified by a slider.
Relevant Code:
girls.dart
class Girls {
String name;
int distance;
Girls(this.name, this.distance);
}
girls_screen.dart
import 'package:flutter/material.dart';
import 'package:switch_circle_color/model/girls.dart';
class GirlsScreen extends StatefulWidget {
GirlsScreen({Key? key}) : super(key: key);
@override
State<GirlsScreen> createState() => _GirlsScreenState();
}
class _GirlsScreenState extends State<GirlsScreen> {
int distance = 15;
void changeDistance(double num) {
setState(() {
distance = num.round();
populateFilteredGirls(distance);
this.filteredGirls = filteredGirls;
});
}
List<Girls> allGirls = [
Girls("Reshmita", 25),
Girls("Ankita", 17),
Girls("Rupali", 42),
Girls("Monica", 50),
Girls("Sakshi", 9)
];
List<Girls> filteredGirls = [];
@override
void initState() {
super.initState();
//filteredGirls = allGirls;
distance = 20;
allGirls.sort((a, b) => a.distance.compareTo(b.distance));
populateFilteredGirls(distance);
}
void populateFilteredGirls(int dis) {
for (int i = 0; i < allGirls.length; i ) {
if (allGirls[i].distance <= dis) {
filteredGirls.add(allGirls[i]);
}
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
children: [
Padding(padding: EdgeInsets.all(20)),
Slider(
min: 1.0,
max: 100.0,
divisions: 100,
activeColor: Colors.green,
inactiveColor: Colors.orange,
label: 'Set distance value',
value: distance.toDouble(),
onChanged: (value) {
changeDistance(value);
},
),
Padding(padding: EdgeInsets.all(10)),
Text("Current distance is $distance kms"),
Padding(padding: EdgeInsets.all(10)),
Expanded(
child: ListView.builder(
itemCount: filteredGirls.length,
itemBuilder: (BuildContext context, int index) {
return ListTile(
leading: const Icon(Icons.girl_outlined),
trailing: Text("${filteredGirls[index].distance} km away"),
title: Text("${filteredGirls[index].name}"),
);
},
),
),
],
),
));
}
}
Issue faced:
When the app loads, I see the two girls who exist within the initially specified distance of 20 km.
However, when I drag the slider, to say, 30 km, the search result with 3 girls repeats after the initial search result of 2 girls.
How do I make sure that upon dragging the slider, only the new search result gets displayed and all previous search results disappear?
CodePudding user response:
clear the list before adding items.
void populateFilteredGirls(int dis) {
filteredGirls.clear();
for (int i = 0; i < allGirls.length; i ) {
if (allGirls[i].distance <= dis) {
filteredGirls.add(allGirls[i]);
}
}
}