Gnziet
Gnziet

Reputation: 355

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).

   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.

    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.

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

Kindly help on how to compare data in Gride view builder. Currently, only one data show "Added" though there are other data too not showing "Added" in view.

Upvotes: 2

Views: 7162

Answers (2)

Sanket Vekariya
Sanket Vekariya

Reputation: 2956

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:
enter image description here

Note: This is a demo code. You can get all the added course ids in alreadyAddedIndices list. Change code as per the need.

Upvotes: 3

Imran
Imran

Reputation: 84

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. If the function returns false only then do you add to the list. Here is an example of a sudo code that return a Text widget:

_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 :)

Upvotes: 0

Related Questions