gpt4 book ai didi

flutter - 如何在类似于搜索字词的位置设置字符串样式

转载 作者:行者123 更新时间:2023-12-03 04:51:34 25 4
gpt4 key购买 nike

我正在使用Flutter,我已经编写了一个用于搜索笔记的小脚本。它工作正常,但我想知道如何为类似于搜索字词的字符串制作颜色样式。

例如,如果我在搜索字段中输入“is” ,那么结果中所有文本中的所有字符串“is” 都应使用不同颜色的和粗体

enter image description here

这是一些脚本:

  // the controller of FieldText is _qController: 
// final _qController = TextEditingController();

body: FutureBuilder(
future: dbmanager.search(_qController.text),
builder: (context, snapshot) {
if (snapshot.hasData) {
noteList = snapshot.data;
return ListView.builder(
shrinkWrap: true,
itemCount: noteList == null ? 0 : noteList.length,
itemBuilder: (context, int index) {
note = noteList[index];
String title = note.title;
String description = note.description;
return Padding(
padding: const EdgeInsets.symmetric(
vertical: 1.0, horizontal: 4.0),
child: Card(
child: ListTile(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => ViewNote(
note: noteList[index],
),
),
);
},
title: Text(title.isNotEmpty ? title : 'Aucun titre'),
subtitle: Text(description.length < 100
? description
: description.substring(1, 100)),
),
),
);
});
}

最佳答案

除了使用Text小部件,您还可以查看RichText,它可以帮助您实现这一目标。您可以具有一个函数,该函数接受您的搜索字符串和要显示的字符串,然后根据突出显示搜索词字符串的RichText小部件进行返回。

以下代码的作用是构建短语“你好,它正在按预期工作”,并以粗体突出显示在TextField中找到的所有单词,这是您可以用来构建文本的逻辑类型的一个小示例。

import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: HomePage(),
);
}
}

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
String searched = "";

@override
Widget build(BuildContext context) {
return Scaffold(
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
TextField(
textAlign: TextAlign.center,
onChanged: (String word) {
setState(() {
searched = word;
});
},
),
SizedBox(height: 100),
buildRichText("hello this is working as intended", searched),
],
),
);
}

checkWordContained(String word, String searched){
for(String searchWord in searched.split(" ")){
if(word == searchWord){
return FontWeight.bold;
}
}
return FontWeight.normal;
}

Widget buildRichText(String phrase, String searched) {
List<InlineSpan> children = [];
for (String word in phrase.split(" ")) {
children.add(
TextSpan(
text: "$word ",
style: TextStyle(
fontSize: 18,
color: Colors.black,
fontWeight: checkWordContained(word,searched)),
),
);
}
return RichText(
textAlign: TextAlign.center,
text: TextSpan(
style: TextStyle(fontSize: 18, color: Colors.black),
children: children,
),
);
}
}

关于flutter - 如何在类似于搜索字词的位置设置字符串样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61276547/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com