我试着用biGram实现全文搜索框,我写了下面的代码;
class SearchScreen extends StatefulWidget {
const SearchScreen({Key? key}) : super(key: key);
@override
State<SearchScreen> createState() => _SearchScreenState();
}
class _SearchScreenState extends State<SearchScreen> {
final TextEditingController searchController = TextEditingController();
bool isShowUsers = false;
Map? searchWords;
bool isLoading = false;
@override
void initState() {
super.initState();
nGram();
}
nGram() async {
setState(() {
isLoading = true;
});
try {
Map searchWords = tokenToSearch(searchTerm: searchController.text);
var query = FirebaseFirestore.instance.collection('posts').limit(30);
searchWords.forEach((word, bool) {
query = FirebaseFirestore.instance
.collection('posts')
.where("token.${word}", isEqualTo: true);
});
var snap = await query.get();
setState(() {});
} catch (e) {
showSnackBar(
context,
e.toString(),
);
}
setState(() {
isLoading = false;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Form(
child: TextFormField(
controller: searchController,
decoration:
const InputDecoration(labelText: 'Search for a description...'),
onFieldSubmitted: (String _) {
setState(() {
isShowUsers = true;
});
print(_);
},
),
),
),
body: isShowUsers
? FutureBuilder(
future: nGram().snap,
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
return ListView.builder(
itemCount: (snapshot.data! as dynamic).docs.length,
itemBuilder: (context, index) {
return ListTile(
title: InkWell(
child: Text(
(snapshot.data! as dynamic).docs[index]
['description'],
),
),
);
},
);
},
)
: FutureBuilder(
future: FirebaseFirestore.instance
.collection('posts')
.orderBy('datePublished')
.get(),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator(),
);
}
return Container();
},
),
);
}
}
发生下列错误;
类别'Future'没有执行严修getter 'snap'。接收端:'Future '的示例尝试调用:弹响
请帮助我。我想知道如何纠正代码。
引用:要搜索的令牌
Map<String,dynamic> tokenToSearch({ required String searchTerm }) {
final int nGramIndex = 2;
final int length = searchTerm.length;
Map<String,dynamic> tokenToSearch = {};
if (length < nGramIndex) {
tokenToSearch[searchTerm] = true;
} else {
int termIndex = 0;
for (int i = 0; i < length - nGramIndex + 1; i++) {
final String key = searchTerm.substring(termIndex,termIndex + nGramIndex);
tokenToSearch[key] = true;
termIndex++;
}
}
return tokenToSearch;
}
1条答案
按热度按时间ryevplcw1#
你的
ngram
函数没有返回任何东西。你需要在它的末尾返回return snap
。最好将
snap
存储在状态中,类似于已经对isLoading
所做的。