Home > other >  Ternary operator inside loop generated 'ListView'
Ternary operator inside loop generated 'ListView'

Time:01-20

Im a flutter beginner, actually to the whole Software development domain,

I have a list generated with a loop, i want to add Divider() after 'Three', and 'Six', preferably using ternary operator, either, or if-else,

You may try the code, by visiting

import 'package:flutter/material.dart';

List<String> items = <String>[
  "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
];

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            for (int i = 0; i < 8; i  )
              ListTile(title: Text(items[i])),
          ],
        ),
      ),
    ),
  );
}

With my current level of knowledge, i tried using Ternary operator, but it made the item 'Three' to be skipped from the list, (actually i know this already, but the problem is that i was not able to add more than one statements in the true part, i tried many ways like (){...}, (){...}(), ...?...:(...?...:...), even ...[...], but each try threw some error)

import 'package:flutter/material.dart';

List<String> items = <String>[
  "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight",
];

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: ListView(
          children: [
            for (int i = 0; i < 8; i  )
              (i == 2)
                  ? const Divider()
                  : ListTile(title: Text(items[i])),
          ],
        ),
      ),
    ),
  );
}

Thanking you...

CodePudding user response:

You want to add Divider after three and six, But using ternary operator, you are replacing the ListTile widget with Divider.

val? true:false, means here only one will be return. What you need to just check the index and add divider only after three and six, if statement is perfect for this as @Josteve mentioned on his answer. While in children can only be widget instead of list, he is using Column to merge Divider and ListTile, you can use spread operator instead.

ListView(
  children: [
    for (int i = 0; i < 8; i  ) ...[
      ListTile(title: Text(items[i])),
      if (i == 2 || i == 5) const Divider()
    ]
  ],
),

You can check more about spread-operator and use cases.

CodePudding user response:

Try this:

for (int i = 0; i < 8; i  ) ...[
    ListTile(title: Text(items[i])),
    if (i == 2 || i == 5) const Divider()
]
  •  Tags:  
  • Related