Home > Mobile >  type 'text' is not a subtype of type 'string'
type 'text' is not a subtype of type 'string'

Time:01-26

I am new on Flutter and i got this error.

type 'text' is not a subtype of type 'string'

I have a class

class _Message {
  int whom;
  String text;

  _Message(this.whom, this.text);
}

and I want to convert the text to a list using this

  @override
  Widget build(BuildContext context) {
    final List<String> led = messages.map((_message) => Text('${_message.text}')).cast<String> 
    ().toList();
  }

How should i solve this?

CodePudding user response:

Text is a Widget so you can't cast it to String.

Text Widgets are used to tell flutter how to render a String. You also need to return a single Widget in the build method.

You probably just want to do

  @override
  Widget build(BuildContext context) {
    return Column(
      children: messages.map((message) => Text(message.text)).toList(),
    );
  }

Optional:

To get that List<String> you do

final List<String> led = messages.map((message) => message.text).toList();

So your build method could look like this:

  @override
  Widget build(BuildContext context) {

    final List<String> led = messages.map((_message) => _message.text).toList();
    return Column(
      children: led.map((message) => Text(message)).toList(),
    );
  }

CodePudding user response:

Text is a widget and not the same as a String Object. Therefore, you cannot assign a list of type Text to a List of type String.

If you mean to return a list of Text widgets, then change List<String> to List<Text>.

And secondly, the build methods requires you return a Widget Object and nothing more.

  •  Tags:  
  • Related