skip to Main Content

I’m pretty new to this and I’m a bit stumped. Trying to have various background colours on gridView items but all the ways I know of don’t seem to work, because the data is coming from firebase.

    var colors = [
    Colors.red,
    Colors.blue,
    Colors.cyan,
    Colors.green,
    Colors.yellow,
  ];

  Widget gridPost(
    String Name,
    String JobTitle,
    String Company,
    String photo,
  ) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        color: colors[index]
      )),}

This doesn’t work because of the ‘index’ part of colors[index]. if I add int index to the gridPost widget, it then wants it also as

  return gridPost(
                    snapshot.data!.docs[index]['index'],)

but that doesn’t work either because that doesn’t exist in Firebase. adding a dummy field to firebase also didn’t work. Please help 🙂

This is more or less what I’m after

This is more less what I'm after

2

Answers


  1. Try to create a method like this :

    List<Color> colors = [
        Colors.red,
        Colors.blue,
        Colors.cyan,
        Colors.green,
        Colors.yellow,
      ];
    
    
    
    Widget gridPost(
        //add other properties that you need
         int index,
        ) {
        return Container(
          decoration: BoxDecoration(
            borderRadius: BorderRadius.all(Radius.circular(20)),
            color: colors[index]
          )),}
    
    

    call method like this :

    return gridPost(snapshot.data!.docs[index]['index'])
    
    Login or Signup to reply.
  2. if you want to create random color and use it in the background you can do it like this

     Widget gridPost(
    String Name,
    String JobTitle,
    String Company,
    String photo,
    ) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        color: Color((math.Random().nextDouble() * 0xFFFFFF).toInt()).withOpacity(1.0)
      )),}
    

    EDIT
    if you want to select from the list try this code:

    Widget gridPost(
    String Name,
    String JobTitle,
    String Company,
    String photo,
     ) {
    return Container(
      decoration: BoxDecoration(
        borderRadius: BorderRadius.all(Radius.circular(20)),
        color: colors[math.Random().nextInt(colors.length)]
      )),}
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search