Flutter:如何删除重复的 Json 对象列表

Kha*_*tri 0 dart flutter

我想仅在项目列表中按名称删除重复的 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});
}
Run Code Online (Sandbox Code Playgroud)

Era*_*han 6

我猜你还没有重写类中的==运算符(因此也重写了hashCodeProfilemodel。因此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();
Run Code Online (Sandbox Code Playgroud)

或者你总是可以尝试覆盖我上面提到的内容。阅读这篇文章以获取更多信息。