#flutter #dart
#флаттер #дротик
Вопрос:
Я хочу удалить дублирующуюся Profilemodel только по имени в списке элементов, поэтому я не должен получать дублирующиеся элементы на экране. Я хочу удалить дублирующуюся Profilemodel только по имени в списке элементов, поэтому я не должен получать дублирующиеся элементы на экране.
Я использовал items.toSet().toList()
, но это не работает с моими потребностями.
Полный код :
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
// Application name
title: 'Flutter Hello World',
// Application theme data, you can set the colors for the application as
// you want
theme: ThemeData(
primarySwatch: Colors.blue,
),
// A widget which will be started on application startup
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
List<Profilemodel> items = [
Profilemodel( age: 20 , name: 'Ahmed' ) ,
Profilemodel( age: 30 , name: 'Fatma' ),
Profilemodel( age: 15 , name: 'Ahmed' ),
Profilemodel( age: 15 , name: 'jon' ),
Profilemodel( age: 25 , name: 'Fatma' )];
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
body : ListView.builder(
itemBuilder: (context, index){
return ListTile(
title: Text('${items[index].name}'),
);
},
itemCount: items.length,
)
);
}
}
class Profilemodel{
final String name;
final int age;
Profilemodel({this.name , this.age});
}
Ответ №1:
Я предполагаю, что вы не переопределили ==
оператор (и, следовательно hashCode
, ) в своем Profilemodel
классе. Следовательно items.toSet().toList()
, может работать не так, как вы ожидали.
Если вам нужно очень простое решение, вы можете попробовать что-то вроде этого,
List<People> items = [
Profilemodel( age: 20 , name: 'Ahmed' ) ,
Profilemodel( age: 30 , name: 'Fatma' ),
Profilemodel( age: 15 , name: 'Ahmed' ),
Profilemodel( age: 15 , name: 'jon' ),
Profilemodel( age: 25 , name: 'Fatma' )
];
final Map<String, People> profileMap = new Map();
items.forEach((item) {
profileMap[item.name] = item;
});
items = profileMap.values.toList();
Или вы всегда можете попытаться переопределить то, что я упомянул выше. Прочитайте эту статью для получения дополнительной информации об этом.
Ответ №2:
Есть много способов, которыми вы можете попытаться удалить дубликаты элементов из списка. например, вы можете преобразовать свой список в набор наборов.
Set<Profilemodel> set = new Set<Profilemodel>.from(items );