Home > Mobile >  Random color in listview data keeps changing while searching?
Random color in listview data keeps changing while searching?

Time:02-23

I have unknown list data fetch from API. Here is my code where I declared random color for the list view.

Widget employeeListBuilder() {
    return Scrollbar(
      isAlwaysShown: true,
      thickness: 6,
      radius: const Radius.circular(10),
      child: ListView.builder(
        itemCount: employee.length,
        itemBuilder: (context, i) {
          return ListViewWidget(
            name: employee[i].name.toString(),
            department: employee[i].department.toString(),
            color: Colors.primaries[Random().nextInt(Colors.primaries.length)] ,
          );
        },
      ),
    );
  }

enter image description here

CodePudding user response:

Try to use below code hope its help to you. Refer Primaries-Constant

color: Colors.primaries[i % Colors.primaries.length],

CodePudding user response:

Many ways are there to get a random color. Some approaches listed below

  • Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)
  • maintain a list with colors you want and get random color from them like below
  List colors = [Colors.red, Colors.green, Colors.yellow];
  Random random = new Random();

  final Color newColor = random.nextInt(3);
  • Random().nextInt(0xffffffff)
  • Related