Flutter - Wrap: do not wrap with text

349 Views Asked by At

i have this code:

import 'package:flutter/material.dart';

void main() => runApp(mainApp());

class mainApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      home: Chat(),
    );
  }
}

class Chat extends StatefulWidget {
  const Chat({Key? key}) : super(key: key);

  @override
  _ChatState createState() => _ChatState();
}

class _ChatState extends State<Chat> {
  List<Container> myList = [
    Container(
      child: Text(
        'Hello, my name ',
        style: TextStyle(fontSize: 25.0),
      ),
    ),
    Container(
      color: Colors.orange,
      child: Text(
        'is',
        style: TextStyle(fontSize: 25.0),
      ),
    ),
    Container(
      child: Text(
        ' Gabriele, and i am 21 years old!',
        style: TextStyle(fontSize: 25.0),
      ),
    ),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Wrap(
          children: myList,
        ),
      ),
    );
  }
}

this is my current output:

enter image description here

and this is the output I would like to get: (I would like the last container of myList not to wrap right away). Anyone know how I can do?

enter image description here

I hope you can help me.

Thank you :)

1

There are 1 best solutions below

2
On BEST ANSWER

You can use RichText instead of Wrap in this case.

RichText(
  text: TextSpan(
    style: TextStyle(fontSize: 25.0),
    children: [
      TextSpan(text: 'Hello, my name '),
      TextSpan(
          text: 'is',
          style: TextStyle(
            backgroundColor: Colors.amber,
          )),
      TextSpan(text: ' Gabriele, and i am 21 years old!'),
    ],
  ),
),

enter image description here

If you need to include others simple beside text, you can wrap the widget with WidgetSpan and use as children on TextSpan.

RichText(
  text: TextSpan(
    style: TextStyle(fontSize: 25.0),
    children: [
      TextSpan(text: 'Hello, my name '),
      WidgetSpan(
          child: Container(
        color: Colors.green,
        width: 40,
        height: 40,
      )),