Home > Mobile >  Flutter: Add a new line in Text Widget
Flutter: Add a new line in Text Widget

Time:11-23

I know there are a lot of questions like this but all those answers did not help me out. I'm receiving two texts from my API backend and when I display them everything works just fine until one of these words are too long. I didn't manage to automatically jump to a new line in that case. This is the relevant part of my code:

Text(
     item.brand   '\n'   item.model,
     style: const TextStyle(
     fontSize: 18,
     fontFamily: 'Avenir',
     fontWeight: FontWeight.bold),
     ),

Can someone please help me out? Thank you so much!

CodePudding user response:

If I understand your question the right way, you want to jump to new line when the text is too long. In that case, you must wrap your text inside a parent widget with a define size, for example a SizedBox :


const SizedBox(
  height: 200,
  width: 200,
  child: Text(
     item.brand   '\n'   item.model,
     style: const TextStyle(
     fontSize: 18,
     fontFamily: 'Avenir',
     fontWeight: FontWeight.bold),
     ))

The text will now jump to a new line when it is longer than 200px

CodePudding user response:

I'm not sure if this answer your question but you can try use this widget below

Text.rich(TextSpan(
    text: "${item.brand}\n",
    style: const TextStyle(
        fontSize: 18, fontFamily: 'Avenir', fontWeight: FontWeight.bold),
    children: [
      TextSpan(
        text: "${item.model}",
        style: const TextStyle(
            fontSize: 18,
            fontFamily: 'Avenir',
            fontWeight: FontWeight.bold),
      ),
    ]));

In this widget you can add diferents styles in your texts, and by using the ${} operator allows you to break the line with \n. Or you can just do this inside your Text widget.

Text(
     "${item.brand}\n${item.model}",
     style: const TextStyle(
     fontSize: 18,
     fontFamily: 'Avenir',
     fontWeight: FontWeight.bold),
     ),

In dart you can use the operator to concatenate Strings, but it's not necessary

  • Related