Home > Net >  Getting index error while list item is less than 3
Getting index error while list item is less than 3

Time:04-18

I am making a game where a screen showing top 3 players...Its working well but showing index error when list item is less than 3.. at this situation, i want output like following

John
No record
No record

import 'package:flutter/material.dart';
import 'datafile.dart';
void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Top 3 Players"),
        ),
        body: ListView.builder(
            itemCount: 3,
            itemBuilder: (context, index) {
              return Text(games[index].player);

            }),
      ),
    );
  }
}

CodePudding user response:

Here is the solution that I found

ListView.builder(
        itemCount: 3,
        itemBuilder: (context, index) {
          return Text(games.length == 3
              ? games[index]
              : (index > games.length - 1)
                  ? 'No Record'
                  : games[index - games.length < 0 ? index : games.length]);
        }),

CodePudding user response:

Since you hardcoded the value of itemCount to 3 it will definitely throw an error if games.length is not equal or greater than 3.

Here's the solution:

      Column(
        children: [
          ListView.builder(
              physics: const NeverScrollableScrollPhysics(),
              shrinkWrap: true,
              itemCount: games.length >= 3 ? 3 : games.length,
              itemBuilder: (context, index) {
                return Text(games[index].player!);
              }),
          if (games.length < 3) ...[
            for (int x = 0; x < (3 - games.length); x  ) ...[
              const Text(
                "No Record!",
              )
            ]
          ],
        ],
  • Related