Last active
November 18, 2021 12:30
-
-
Save bobagold/9b379772ea5399d2c439697d26ebf0c3 to your computer and use it in GitHub Desktop.
Parse string to rich text
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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