Skip to content

Instantly share code, notes, and snippets.

@LordOlumide
Created October 26, 2024 07:06
Show Gist options
  • Select an option

  • Save LordOlumide/77df7483e28594787c4e7b328aabf1d7 to your computer and use it in GitHub Desktop.

Select an option

Save LordOlumide/77df7483e28594787c4e7b328aabf1d7 to your computer and use it in GitHub Desktop.
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: const Text('Example')),
body: ExampleBody(),
),
);
}
}
class ExampleBody extends StatelessWidget {
ExampleBody({super.key});
final TextEditingController controller = TextEditingController();
final FocusNode focusNode = FocusNode();
final String exampleText = 'This is the first line.\\nThis is the second.'
'\\nThis is the third.\\nThis is \\nthe broken.';
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(exampleText),
const SizedBox(height: 10),
RichText(
text: TextSpan(
children: RichLogic.applyFormatting(input: exampleText),
style: TextStyle(color: Colors.black),
),
),
const SizedBox(height: 10),
Text(RichLogic.removeAllSpecialFormatting(exampleText)),
],
),
);
}
}
abstract class RichLogic {
static String pattern = '\\n';
static String removeAllSpecialFormatting(String text) =>
text.replaceAll(pattern, '');
static List<TextSpan> applyFormatting({required String input}) {
List<TextSpan> spans = [];
List<String> pieces = input.split(pattern);
spans = pieces.map((piece) => TextSpan(text: '$piece\n')).toList();
return spans;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment