'How to generate List<TextSpan> dynamic?

Good Morning everyone,

I Have different words of different lengths and I Need to create a dynamic List of TextSpan with every letter from the current word.

I have Example to clear what i mean with screenshot

  var txtColor = 'a';
  var word = 'rate'.split('');

  levlup() {
    List<TextSpan> textSpans = <TextSpan>[
      TextSpan(text: word[0], style: TextStyle(color: txtColor == word[0] ? Colors.red: Colors.black)),
      TextSpan(text: word[1], style: TextStyle(color: txtColor == word[1] ? Colors.red: Colors.black)),
      TextSpan(text: word[2], style: TextStyle(color: txtColor == word[2] ? Colors.red: Colors.black)),
      TextSpan(text: word[3], style: TextStyle(color: txtColor == word[3] ? Colors.red: Colors.black)),

    ];
    return textSpans;
  }

  Widget build(BuildContext context) {

    return Scaffold(
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            RichText(
              text: TextSpan(
                style: TextStyle(color: Colors.black, fontSize: 18),
                children: levlup(),
              ),
            )
          ],
        ),
      ),
    );
  }
}

enter image description here



Solution 1:[1]

something like this?

List<TextSpan> textSpans = word.map((c) => TextSpan(text: c, style: TextStyle(color: txtColor == c ? Colors.red: Colors.black))).toList();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ivo Beckers