skip to Main Content

It is a text editing app. I want to change my text color. I can’t figure out what the error is.

      List<TextInfo> texts = [];
      int currentIndex = 0;
    
        changeTextColor(Color color) {
        setState(() {
          texts[currentIndex].color = color; //it works
        });
      }

      changeTextColor1(context) {
        Widget buildColorPicker() {
          return ColorPicker(
            pickerColor: texts[currentIndex].color, //there
            onColorChanged: (color) => setState(
              () => texts[currentIndex].color = color, //there     
            ),
          );
        }

I tried to assign the color of the current text to the variable.

Color pcolor = texts[currentIndex].color;

2

Answers


  1. If you have a list such as your "texts" variable, when you write code such as texts[0], you are actually trying to retrieve the first element in that list. But since the list is empty, that would result in a RangeError.

    Since your texts list is empty and currentIndex is 0, your code texts[currentIndex] will generate a RangeError.

    Login or Signup to reply.
  2. Precheck with texts.isNotEmpty() or List texts = [TextInfo()].

    Gather and process overlapping locations in one place.

    changeTextColor(Color color){
        if (texts.isEmpty()) return;
        texts[currentIndex].color = color;
    }
    ....
    ....
    setState(()=> changeTextColor(color));
    

    Have a happy coding life. 🙂

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search