我正在尝试实现搜索功能,并希望从API中获取结果。
在方法buildResults()下,您会发现我的注释//数据为空,但是问题是我正在从API调用中获取数据。我在这里想念东西吗?
在buildsResults()下,我正在调用Future _getResults并返回接收到的数据。我记录了您可以看到的数据。
class SearchBar extends StatefulWidget {
@override
_SearchBarState createState() => new _SearchBarState();
}
class _SearchBarState extends State<SearchBar> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
iconTheme: new IconThemeData(color: Theme.of(context).hintColor),
elevation: 1,
backgroundColor: Theme.of(context).primaryColor,
actions: <Widget>[
IconButton(
autofocus: true,
icon: Icon(Icons.search),
onPressed: () async {
final results = await showSearch<SearchModel>(context: context, delegate: DataSearch(context));
})
],
centerTitle: true,
title: Text('Search content'),
),
);
}
}
class DataSearch extends SearchDelegate<SearchModel> {
final BuildContext parentContext;
final Logger logger = new Logger();
DataSearch(this.parentContext);
@override
List<Widget> buildActions(BuildContext context) {
return [
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = "";
},
)
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: AnimatedIcon(
icon: AnimatedIcons.menu_arrow,
progress: transitionAnimation,
),
onPressed: () {
Navigator.pop(context);
Navigator.pop(parentContext);
},
);
}
@override
Widget buildResults(BuildContext context) {
return FutureBuilder<List<SearchModel>>(
future: _getResults(),
builder: (context, AsyncSnapshot<List<SearchModel>> snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
logger.d(snapshot.hasData);
return ListView.builder(
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data[index].title),
onTap: () {
close(context, snapshot.data[index]);
},
);
},
itemCount: snapshot.data.length, // data is null
);
} else {
return Center(
child: CircularProgressIndicator(),
);
}
},
);
}
@override
Widget buildSuggestions(BuildContext context) {
return Container();
}
Future<List<SearchModel>> _getResults() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
String language = prefs.getString('language');
var data;
await http.get(Constants.BASE_URL + "/search/" + language + "/" + query,).then((response) {
data = convert.jsonDecode(response.body) as List;
});
logger.d(data);
return data.map((model) => SearchModel.fromJson(model)).toList();
}
}
答案 0 :(得分:0)
我认为是这样的:
onTap: () async {
final results = await showSearch(context: context, delegate: SearchBar(),query:query);
}
结果获取返回值 查询是传递的参数