Home > Mobile >  How to add multiple attributes to Text in Flutter?
How to add multiple attributes to Text in Flutter?

Time:09-29

I am constantly getting errors in Flutter.

Text(widget.time != null? "${widget.time!.count ?? 0} hours"

The above works perfectly.

However, I do not want to hardcode 'hours', as I will need it for translation. So, I am trying the following:

Text(widget.time != null? "${widget.time!.count ?? 0}" : (Localized.of(context)!.trans(LocalizedKey.locationContact) ?? ""),

But whatever I do, I am getting errors like:

"Expected to find ')'

and

"expected an identifier"

How can I resolve this?

I have the same case with:

List<Option> timeOptions = [
    Option(title: Text(Localized.of(context)!.trans(LocalizedKey.locationContact) ?? ""), isSelected: false, key: "free")
];

It gives me the following errors:

error: The argument type 'Text' can't be assigned to the parameter type 'String?'.

And:

error: The instance member 'context' can't be accessed in an initializer.

CodePudding user response:

The first error : You may defined Option like Option({String title}) So the construction should be like

List<Option> timeOptions = [
    Option(title: Localized.of(context)!.trans(LocalizedKey.locationContact ?? ""), isSelected: false, key: "free")
];

Or defined constructor like Option({Widget title})

For the second error :

You may coding like

  List<Option> timeOptions = [
      Option(title: Localized.of(context)!.trans(LocalizedKey.locationContact ?? ""), isSelected: false, key: "free")
  ];
  @override
  Widget build(BuildContext context) {

      ```
  }

Please change it inside build

  List<Option> timeOptions = [];
  @override
  Widget build(BuildContext context) {
  timeOptions  = [
      Option(title: Localized.of(context)!.trans(LocalizedKey.locationContact ?? ""), isSelected: false, key: "free")
  ];
      ```
  }
  • Related