skip to Main Content

I have a list in a Provider that I’m adding to using the following code:

context.read<LogProvider>().LogInfoList.add(Entries(
                                  text: 'Specific Entry 01',
                                  logID: 'SELECT ENTRY'));

because I’m adding so many variables to the list, I’ve included a logID variable so I can use it to find the specific entry in other parts of my code.

Now when the user selects another entry from the list, I first want it to check if the logID is already on the list, and if it is replace it or create a new Entry.

here is what I have so far.

onTap: () 
{if(context.read<LogProvider>().LogInfoList.contains(logID == 'SELECT ENTRY')){
context.read<LogProvider>().LogInfoList.replaceRange(index, index + 1, replacements)
}else{
context.read<LogProvider>().LogInfoList.add(Entries(
                                  text: 'Specific Entry 01',
                                  logID: 'SELECT ENTRY'));
}

I think I’m on the right track using .contains and .replaceRange but am unsure how to implement the code to make it work.

any help would be greatly appreciated

3

Answers


  1. instead of this part of code:

    if(context.read<LogProvider>().LogInfoList.contains(logID == 'SELECT ENTRY')
    

    use this one:

    if(context.read<LogProvider>().LogInfoList.logID.contains('SELECT ENTRY')
    
    Login or Signup to reply.
  2. try the below and let me know.

    //either this
    final element = LogInfoList.firstWhere((item) => item['logID'] == 'SELECT ENTRY', orElse: () => null);
    //or this
    final element = LogInfoList.firstWhere((item) => item.logID == 'SELECT ENTRY', orElse: () => null);
    
    if (element != null){
         LogInfoList.remove(element);
    }else{
         LogInfoList.add(Entries(text: 'Specific Entry 01',
                                  logID: 'SELECT ENTRY'));
     }
    
    Login or Signup to reply.
  3. You can refer to below code:

    // index which have the logId as 'SELECT ENTRY'
    // will return -1 if there's no element with 'SELECT ENTRY' logId
    final index = entriesList.indexWhere((entry) => entry.logID == 'SELECT ENTRY');
    
    if (index != -1) {
       // update
       entriesList[index].text = newText;
    } else {
       // insert
       entriesList.add(Entries(text: 'Specific Entry 01', logID: 'SELECT ENTRY'));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search