我想搜索我的内容,但是我的代码遇到问题。当我单击搜索图标时,它首先不显示任何数据,然后显示错误(引发了另一个异常:类型'(dynamic)=> dynamic'不是'test'类型'(Book)=> bool'的子类型')。
我这样在主屏幕的AppBar上创建一个搜索图标-
actions: <Widget>[
FutureBuilder(
future: fetchBooks(http.Client()),
builder: (context, snapshot) {
return IconButton(
icon: Icon(Icons.search),
onPressed: () {
showSearch(
context: context,
delegate: BooksSearch(snapshot.data));
},
);
}),
],
这是我的模特。飞镖-
import 'dart:async';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;
Future<List<Book>> fetchBooks(http.Client client) async {
final response =
await client.get('https://boimarket.abirahsan.com/public/api/v1/books');
// Use the compute function to run parsePhotos in a separate isolate.
return compute(parseBooks, response.body);
}
// A function that converts a response body into a List<Photo>.
List<Book> parseBooks(String responseBody) {
final parsed = jsonDecode(responseBody).cast<String, dynamic>();
return parsed['data'].map<Book>((json) => Book.fromJson(json)).toList();
}
class Book {
final String name;
final String author;
final String html;
final String description;
final int category;
Book({
this.name,
this.author,
this.description,
this.html,
this.category,
});
factory Book.fromJson(Map<String, dynamic> json) {
return Book(
name: json['name'] as String,
html: json['html'] as String,
description: json['description'] as String,
author: json['author'] as String,
category: json['category'] as int,
);
}
}
这是我的booksearch.dart-
import 'package:flutter/material.dart';
import 'package:boimarket/model/model.dart';
import 'package:http/http.dart' as http;
class BooksSearch extends SearchDelegate<Book> {
BooksSearch(this.allBooksData);
final allBooksData;
@override
List<Widget> buildActions(BuildContext context) {
return [
SizedBox(
width: 5.0,
),
IconButton(
icon: Icon(Icons.clear),
onPressed: () {
query = '';
},
)
];
}
@override
Widget buildLeading(BuildContext context) {
return IconButton(
icon: Icon(Icons.arrow_back),
onPressed: () {
close(context, null);
},
);
}
@override
Widget buildResults(BuildContext context) {
return Container();
}
@override
Widget buildSuggestions(BuildContext context) {
return FutureBuilder(
future: fetchBooks(http.Client()),
builder: (context, snapshot) {
if (!snapshot.hasData) {
return Center(
child: Text('No Data'),
);
} else {
final result = allBooksData
.where((a) => a.name.toLowerCase().contains(query))
.toList();
return ListView(
children: result.map<Widget>((a) => Text(a.name)),
);
}
});
}
}
我的代码中的问题在哪里? 我该如何解决这个错误?