Skip to content

How can I use switch statement to change listview colors  #1

Open

Description

@ABINASH56

here is the code .i need help in switch case. I watched this video but I need more examples to completely understand switch case..

How can i use switch case to change bg color of listview .I want to add 10 different types of colors in listview


ListView.builder(
  itemBuilder: (BuildContext context, int index) {
    return Container(
      color: (index % 10 == 0) ? Colors.red : Colors.green,
      child: ListTile(
        title: ...
      ),
    );
  },
)

Activity

  1. cv692001 commented on Aug 20, 2020

    @cv692001

    Hey @ABINASH56 you can follow up with the following code .I hope this might helps you 👍

    ListView.builder(
    itemBuilder: (BuildContext context, int index) {
    return Container(
    color: (index % 10 == 0) ? Colors.red : Colors.green,
    child: ListTile(
    title: Text(string),
    onTap: () => setState(() => null ),
    selected: null,
    style: ListTileTheme(selectedColor: Colors.white,),
    );
    );
    },
    )

  2. cv692001 commented on Aug 20, 2020

    @cv692001

    Also I am new to contributing , cam you please help me out to contribute further :)

  3. cv692001 commented on Sep 2, 2020

    @cv692001

    Hey @ABINASH56 , have you see it

  4. shatanikmahanty commented on Nov 15, 2020

    @shatanikmahanty

    Hi @ABINASH56 I have a solution for you :

    You can try this code out and see the output. This is how you can use function in dart to get Colors from switch

    import 'package:flutter/material.dart';
    
    main() {
      runApp(
        MaterialApp(
          home: SwitchColors(),
        ),
      );
    }
    
    class SwitchColors extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          backgroundColor: Colors.white,
            body: ListView.builder(
          itemCount: 5,
              shrinkWrap: true,
          itemBuilder: (BuildContext context, int index) {
            return Container(
                color: getColor(index),
                child: ListTile(
                  title: Text("string")
                ));
          },
        ));
      }
    
      Color getColor(int index) {
        switch (index) {
          case 0:
            return Colors.amber;
          case 1:
            return Colors.blue;
          case 2: return Colors.green;
          case 3: return Colors.grey;
          case 4: return Colors.purple;
          default:
            return Colors.white;
        }
      }
    }
    
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions