【问题标题】:How to compare two list data in flutter (dart)如何在颤振(飞镖)中比较两个列表数据
【发布时间】:2020-06-09 10:41:51
【问题描述】:

我的页面上有一个网格数据。我想将这些数据与另一个列表(例如 (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']),

            ],
          ),
        ),

      );
    },
  ),

这是从 firebase 数据库获取的另一个列表数据。

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

    });
   });
   }

以上两个列表都使用数据 ID 进行比较。

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

请帮助您了解如何在 Gride view builder 中比较数据。目前,只有一个数据显示“已添加”,但还有其他数据也未显示“已添加”。

【问题讨论】:

  • 您需要遍历您的一个列表并检查其他列表中是否存在相同的ID。目前在列子中,您只有一件事。一旦您遍历该列表并返回这些小部件的列表,您将有多个孩子。
  • 如何在这里创建循环请帮助我
  • 表示点击课程卡片,您是否要添加文字。对吗?
  • 在学生表中添加的点击卡片课程如果学生已经添加了课程,则会显示课程中添加的消息。

标签: flutter dart


【解决方案1】:

我创建了一个演示。根据您的要求进行更改。

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"),
                      ],
                    ),
                  ),

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

输出:

注意: 这是一个演示代码。您可以在 alreadyAddedIndices 列表中获取所有添加的课程 ID。根据需要更改代码。

【讨论】:

  • 感谢您的回答,但问题是我从 firebase 云存储中获取了一些 id 并存储在一个列表中,现在这个列表与主页上可用的课程 id 进行比较,我需要一个循环来比较或任何其他方式我现在没有。请帮帮我。
【解决方案2】:

线,

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

只比较一个值,因为您只迭代一个列表。尝试通过遍历两个列表来调用返回布尔值或文本小部件的方法。如果函数仅返回 false,那么您是否添加到列表中。下面是一个返回 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");
      }
        }

您可以通过以下方式调用该方法:

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

希望有帮助:)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-12
    • 2021-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-05
    • 1970-01-01
    相关资源
    最近更新 更多