Home > OS >  How to check if an index before a list item exists?
How to check if an index before a list item exists?

Time:04-04

I have a list of objects with keys title, text and title again:

"data": [
        {
          "type": "title",
          "data": "Dashboard"
        },
        {
          "type": "text",
          "data": "This is your dashboard.."
        },
        {
          "type": "title",
          "data": "Fees"
        },
]

I am able to show these key values of key data on the screen:

enter image description here

I want to have a space between text and title if title comes after text. So i made an if else statement which substracts the index with 1 and check if the previous index contains key value text and then i want to show a SizedBox else i want to show an empty Container:

if ((json[index - 1]['type'] == "text") 
    
   SizedBox(height: 10)
else 
   Container(),

But i get error: RangeError (index): Invalid value: Not in inclusive range 0..3: -1 This means that it also substracts the first index with the key value title and that is the reason i get index vallue -1 back. So my question is how can i show SizedBox after text and then also resolve the error above?

CodePudding user response:

that's easily fixed by checking if the index is not 0, so change it to

if (index != 0 && json[index - 1]['type'] == "text") 
  • Related