Show a list of text like a complete paragraph in a list view

Viewed 32

I have a long list of text. For ex like this list below:

["This is a sentence",
"This is a sentence",
"This is a sentence",
"This is a sentence",
"This is a sentence",
"This is a sentence",
"This is a sentence"]

I am using ListView.builder to show this list in my app. And it looks like this below:

This is a sentence //These are ListTiles
This is a sentence
This is a sentence
This is a sentence
This is a sentence
This is a sentence
This is a sentence

But I want to show them like a paragraph instead of individual list tiles. For ex like this:

This is a sentence This is a 
sentence This is a sentence
This is a sentence This is a 
sentence This is a sentence

All the list tile are wrapped with a GestureDetector() and onTap: I do something. This is why I can't use list.join() and show them in a single text widget. How can I achieve this? As all the text in the list need to be separate as I do something depending on the text that has been clicked on. But I also want it to look like a paragraph.

1 Answers

You can do it using TextSpans. Here's a full working example:

import 'package:collection/collection.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(const MaterialApp(
      home: Scaffold(
    body: Center(
      child: SizedBox(width: 200, child: Test()),
    ),
  )));
}

class Test extends StatelessWidget {
  final data = const [
    "This is a sentence",
    "This is a sentence",
    "This is a sentence",
    "This is a sentence",
    "This is a sentence",
    "This is a sentence",
    "This is a sentence"
  ];

  const Test({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text.rich(TextSpan(
        children: data
            .mapIndexed((i, e) => TextSpan(
                text: e,
                recognizer: TapGestureRecognizer()
                  ..onTap = () {
                    print('tapped sentence $i');
                  }))
            .toList()));
  }
}

Output:

enter image description here

Each part will cause a different number to be printed on tap.

Related