I'm new to flutter and I'm building a program that puts text in Textfield and searches for it in algolia.
It works fine up to the point where I enter text and algolia processes it, but it doesn't return any results and nothing is displayed on the screen.
Is it because I am using Stream Builder? (Would Futurebuilder be better?) I'm not sure, so I would appreciate it if someone could help me.
import 'dart:async';
import 'package:algolia/algolia.dart';
import 'package:flutter/material.dart';
import '../../main.dart';
class Application {
static final Algolia algolia = Algolia.init(
applicationId: '78CZVABC2W',
apiKey: 'c2377e7faad9a408d5867b849f25fae4',
);
}
class Search extends StatefulWidget {
@override
_SearchState createState() => _SearchState();
}
class _SearchState extends State<Search> {
StreamController<List<AlgoliaObjectSnapshot>> searchController = StreamController();
Future searchFireStore(word) async {
Algolia algolia = Application.algolia;
AlgoliaQuery query = algolia.instance.index("rigaku_index").query(word);
AlgoliaQuerySnapshot snap = await query.getObjects();
List<AlgoliaObjectSnapshot> hits = snap.hits;
searchController.add(hits);
print(hits.length);
}
final _algilia = Application.algolia;
@override
void dispose() {
searchController.close();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: SearchItems(),
backgroundColor: Colors.white,
),
body: Column(
children: <Widget>[
Expanded(
child: StreamBuilder(
stream: searchController.stream,
builder: (context,AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
itemCount: snapshot.data.length,
itemBuilder: (context, index) {
return Text((snapshot.data[index].data['zyugyoumei']));
},
);
} else {
return Center(
child: Text("No Data"),
);
}
},
),
)
],
),
);
}
}
class SearchItems extends StatefulWidget {
@override
_SearchItemsState createState() => _SearchItemsState();
}
class _SearchItemsState extends State<SearchItems> {
String searchWord = "";
@override
Widget build(BuildContext context) {
return TextField(
decoration: const InputDecoration(
hintText: '検索',
),
controller: TextEditingController(text: searchWord),
onChanged: (String text) {
setState(() {
searchWord = text;
});
},
onSubmitted: (searchWord) =>_SearchState().searchFireStore(searchWord)); }
}
There are no error messages, but the snapshot in the StreamBuilder is null. The [hits] in Future is displayed correctly.