简体   繁体   English

如何比较 flutter 中的两个列表数据(飞镖)

[英]How to compare two list data in flutter (dart)

I have a grid data on my page.我的页面上有一个网格数据。 I want to compare these data to another list like (id 1,2,3,4,5).我想将这些数据与另一个列表(例如(id 1,2,3,4,5))进行比较。

   GridView.builder(
       itemCount: course == null ? 0 : course.length,
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: (MediaQuery.of(context).orientation == Orientation.portrait) ? 3 : 4),
    itemBuilder: (BuildContext context, int index) {
      return Card(
        child:InkWell(
      onTap: () {
        setState(() {
          courseid = course[index]['id'];
          coursename=course[index]['name'];
        });
       addCourse(course[index]['about']);
      },
          child:Column(
            children: <Widget>[
           Text((coursedata['courseid'] == course[index]['id']) ? "Added" : ""),
         IconButton(
                icon: index.isEven ? Icon(Icons.school) : Icon(Icons.book),
                iconSize:MediaQuery.of(context).orientation == Orientation.portrait ?30 : 30,
                color: index.isOdd  ? Colors.amber[800]: Colors.green[800],
                onPressed: (){
                  getcourseData();
                },
              ),
              Text(course[index]['name']),

            ],
          ),
        ),

      );
    },
  ),

This is another list data gets from a firebase database.这是从 firebase 数据库获取的另一个列表数据。

    getcourseData() async {
     databaseReference.collection(user.email).getDocuments().then((querySnapshot) {
    querySnapshot.documents.forEach((result) {
    coursedata=result.data;

    });
   });
   }

Both the above lists are compared using data ids.上述两个列表都使用数据 ID 进行比较。

  coursedata['courseid'] == course[index]['id']) ? "Added" : ""

Kindly help on how to compare data in Gride view builder .请帮助如何在Grid view builder中比较数据。 Currently, only one data show "Added" though there are other data too not showing "Added" in view.目前,只有一个数据显示“已添加”,尽管还有其他数据也未显示“已添加”。

I have created a demo.我创建了一个演示。 Change as per your requirement.根据您的要求进行更改。

import 'package:flutter/material.dart';

void main() =>
  runApp(MaterialApp(home: GridViewDemo()));

class GridViewDemo extends StatefulWidget {
  @override
  _GridViewDemoState createState() => _GridViewDemoState();
}

class _GridViewDemoState extends State<GridViewDemo> {
  // already added indices numbers
  List<int> alreadyAddedIndices = [3,4,5,6,7];

  var courseid = 0;
  var coursename = "default";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(("GridView Demo")),
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            GridView.builder(
              itemCount: 5,
              shrinkWrap: true,
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: (MediaQuery.of(context).orientation == Orientation.portrait) ? 3 : 4),
              itemBuilder: (BuildContext context, int index) {
                return Card(
                  child:InkWell(
                    onTap: () {
                      setState(() {
                        // change as per your code
                        courseid = index;
                        coursename=index.toString();
                        // add index in list if not available
                        // tapping again, remove index from list
                        alreadyAddedIndices.contains(index)?alreadyAddedIndices.remove(index):alreadyAddedIndices.add(index);
                      });
                    },
                    child:Column(
                      children: <Widget>[
                        Text((alreadyAddedIndices.contains(index)) ? "Added" : ""),
                        Icon(index.isEven ? Icons.school : Icons.book,
                          size:MediaQuery.of(context).orientation == Orientation.portrait ?30 : 30,
                          color: index.isOdd  ? Colors.amber[800]: Colors.green[800],),
                        // course name text
                        const Text("course Name"),
                      ],
                    ),
                  ),

                );
              },
            ),
          ],
        ),
      ),
    );
  }
}

Output: Output:
在此处输入图像描述

Note: This is a demo code.注意:这是一个演示代码。 You can get all the added course ids in alreadyAddedIndices list.您可以在 alreadyAddedIndices 列表中获取所有添加的课程 ID。 Change code as per the need.根据需要更改代码。

The line,线,

Text((coursedata['courseid'] == course[index]['id']) ? "Added" : ""), 

is only comparing one value as you are iterating over only one list.只比较一个值,因为您只迭代一个列表。 Try calling a method that returns a boolean value or a Text widget by iterating over both the lists.尝试通过遍历两个列表来调用返回 boolean 值或文本小部件的方法。 If the function returns false only then do you add to the list.如果 function 返回 false ,那么您是否添加到列表中。 Here is an example of a sudo code that return a Text widget:下面是一个返回 Text 小部件的 sudo 代码示例:

_ComparingLists(int id) {
bool temp = false;
  for (int i = 0; i < coursedata['courseid'].length; i++) {
  if ((coursedata['courseid'][i] == id)) {
  temp = true;
  break;
} else {
  temp = false;
}
 }

 // student is already enrolled
 if (temp == true) {
   return Text("Student is enrolled ...");
  }
  // student is not enrolled
  else {
  // do your operations like adding to the list here ....
   return Text("No match");
      }
        }

You can call the method by:您可以通过以下方式调用该方法:

_ComparingLists(course[index]['id'])

Hope that helps:)希望有帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM