extended_text_field
包。结果:
每当出现 @
符号时,它将在一个 Chip
中:
您需要扩展 SpecialTextSpanBuilder
并重写 build
方法:
class MySpecialTextSpanBuilder extends SpecialTextSpanBuilder {
@override
TextSpan build(String data,
{TextStyle? textStyle, SpecialTextGestureTapCallback? onTap}) {
final lookingFor = "@";
final splitData = data.split(" ");
final spans = splitData.map((e) {
if (e == lookingFor) {
return WidgetSpan(
child: Chip(
label: Text(e),
),
);
} else {
return TextSpan(
text: e,
style: TextStyle(color: Colors.red),
);
}
}).toList();
return TextSpan(children: spans, style: textStyle);
}
@override
SpecialText? createSpecialText(String flag,
{TextStyle? textStyle,
SpecialTextGestureTapCallback? onTap,
required int index}) {
// TODO: implement createSpecialText
throw UnimplementedError();
}
}
@
符号,那么我们将使用该数据创建一个Chip
,否则,我们将添加实际文本。MySpecialTextSpanBuilder
类:Scaffold(
backgroundColor: Colors.blue,
body: ExtendedTextField(
style: TextStyle(color: Colors.red),
decoration: InputDecoration(
border: OutlineInputBorder(),
),
specialTextSpanBuilder: MySpecialTextSpanBuilder(),
),
)
import 'package:extended_text_field/extended_text_field.dart';
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
dividerColor: Colors.green,
scaffoldBackgroundColor: darkBlue,
),
debugShowCheckedModeBanner: false,
home: SafeArea(
child: Scaffold(
backgroundColor: Colors.blue,
body: ExtendedTextField(
cursorColor: Colors.black,
style: TextStyle(color: Colors.red),
decoration: InputDecoration(
border: OutlineInputBorder(),
),
specialTextSpanBuilder: MySpecialTextSpanBuilder(),
),
),
),
);
}
}
class MySpecialTextSpanBuilder extends SpecialTextSpanBuilder {
@override
TextSpan build(String data,
{TextStyle? textStyle, SpecialTextGestureTapCallback? onTap}) {
final lookingFor = "@";
final splitData = data.split(" ");
final spans = splitData.map((e) {
if (e == lookingFor) {
return WidgetSpan(
child: Chip(
label: Text(e),
),
);
} else {
return TextSpan(
text: e,
style: TextStyle(color: Colors.red),
);
}
}).toList();
return TextSpan(children: spans, style: textStyle);
}
@override
SpecialText? createSpecialText(String flag,
{TextStyle? textStyle,
SpecialTextGestureTapCallback? onTap,
required int index}) {
// TODO: implement createSpecialText
throw UnimplementedError();
}
}
您可以使用RichText
作为子元素和WidgetSpan
一起使用:
一个不可变的小部件,嵌入文本中。
结果
代码
RichText(
text: TextSpan(
children: [
TextSpan(
text: "one",
),
WidgetSpan(
child: Chip(
label: Text("two"),
),
),
TextSpan(
text: "three",
),
],
),
)
MySpecialTextSpanBuilder
创建一个构造函数,并传入你要查找的内容。 - MendelGsplit(" ")
方法,以便根据完整单词或包含某个单词来进行拆分。 - MendelG