al246
al246

Reputation: 230

Flutter- How to have differing Text Styles in List

I have a list that is populated with the return data of various var's

This list also has a text element preceding the data

I want to have separate weight, size etc for the initial text and then the String being passed in

I have tried RichText and TextStyle but needed a text function, not a list for it to work correctly

Here is the List which is then passed into a function which pushes it to ShowDialog

For example, Line: to be FontWeight.w600 & $pln String to be FontWeight.w400

List data = [
    "Line: $pln", 
    "Departed from: $originname",
    "Destination: $destname",
    "Last seen: $recordedattime",
    ];

ShowDialog, where message is the list from previous function

title: Text(title),
          content: SingleChildScrollView(
            child: ListBody(
              children: <Widget>[
                Text(message,
                style: TextStyle(
              fontSize: 18,
              color: Color(0xff2F2F2F),
              fontWeight: FontWeight.w500,
              ...

Upvotes: 0

Views: 571

Answers (1)

Leonardo Ugiete
Leonardo Ugiete

Reputation: 51

Try creating a new widget for it, this way you can modify the build however you desire easily.

class NewTextWidget extends StatelessWidget {
  final String prefix;
  final String value;

  NewTextWidget({required String message, Key? key})
      : prefix = message.split(": ")[0],
        value = message.split(": ")[1],
        super(key: key);

  @override
  Widget build(BuildContext context) {
    return RichText(
      text: TextSpan(
          text: prefix,
          style: const TextStyle(fontWeight: FontWeight.w600),
          children: [
            TextSpan(
                text: value,
                style: const TextStyle(fontWeight: FontWeight.w400))
          ]),
    );
  }
}

The NewTextWidget expects the message with the prefix: value format.

So when you call it you need to update your ListBody as:

ListBody(
  children: data.map((String message) => NewTextWidget(message: message)).toList()
)

Upvotes: 1

Related Questions