【发布时间】:2021-04-03 21:12:42
【问题描述】:
我试图特别突出两个字母“Rs”,任何特殊字符,如“% 或!”以及 1234 等数字。
我已经从这个问题中得到了一半的答案 - How to highlight text in Flutter? 但我不知道如何为字母编辑它,因为我是 RegEx 的新手?
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: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String str = "Hey I'm 1234 and %";
int findLen(String word) {
return word.replaceAll(new RegExp(r'[a-zA-Z]'), "").length;
}
var styleOne = TextStyle(color: Colors.black87, fontSize: 21);
var styleTwo = TextStyle(
color: Colors.black87, fontWeight: FontWeight.w800, fontSize: 24);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: RichText(
overflow: TextOverflow.ellipsis,
textAlign: TextAlign.center,
maxLines: 4,
text: TextSpan(
children: str
.split(" ")
.map((word) => TextSpan(
text: word + " ",
style: findLen(word) != word.length ? styleOne : styleTwo))
.toList(),
),
),
);
}
}
【问题讨论】: