[英]How to add a widget, like a chip or container, to a textfield in flutter
extended_text_field
package。结果:
只要有@
符号,它就会在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
class:
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();
}
}
Text
小部件您可以将RichText
与WidgetSpan
作为子项一起使用:
内嵌在文本中的不可变小部件。
结果
代码
RichText(
text: TextSpan(
children: [
TextSpan(
text: "one",
),
WidgetSpan(
child: Chip(
label: Text("two"),
),
),
TextSpan(
text: "three",
),
],
),
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.