Skip to content

Instantly share code, notes, and snippets.

@bobagold
Last active November 18, 2021 12:30
Show Gist options
  • Save bobagold/9b379772ea5399d2c439697d26ebf0c3 to your computer and use it in GitHub Desktop.
Save bobagold/9b379772ea5399d2c439697d26ebf0c3 to your computer and use it in GitHub Desktop.
Parse string to rich text
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
debugShowCheckedModeBanner: false,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
@immutable
class MyHomePage extends StatelessWidget {
final String title;
const MyHomePage({
Key? key,
required this.title,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: const [
RandomTextWithIcon("any random string with a πŸ” inside"),
RandomTextWithIcon("any random string ending with a 🎁"),
RandomTextWithIcon("any random string without smiles πŸ³οΈβ€πŸŒˆ"),
],
),
),
);
}
}
@immutable
class RandomTextWithIcon extends StatelessWidget {
final String text;
const RandomTextWithIcon(this.text);
InlineSpan _byPlaceholder(String text) {
switch(text) {
case 'πŸ”': return const WidgetSpan(child: Icon(Icons.add));
case '🎁': return const WidgetSpan(child: Icon(Icons.power));
default: return TextSpan(text: text);
}
}
@override
Widget build(BuildContext context) {
return Text.rich(TextSpan(
children: text
.split(' ')
.map(_byPlaceholder)
.expand((a) => [a, const TextSpan(text: ' ')])
.toList()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment