我遇到以下错误:
在构建FutureBuilder时引发了以下_TypeError(脏,状态:_FutureBuilderState#0e8bb): '_InternalLinkedHashMap
'类型不是'Comparable'类型的子类型
当我尝试做的是使用本地Json的FutureBuilder构建Listview时,如果用户点击菜单进行排序,则对项目进行排序:
class _ResultScreenState extends State<ResultScreen> {
List showData;
var sortedData;
bool byName = false;
bool byRating = false;
@override
void initState() {
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Stack(
children: <Widget>[
ConstrainedBox(
constraints: const BoxConstraints.expand(),
child: Image(
fit: BoxFit.cover,
image: AssetImage('assets/scuba.jpg'),
),
),
Scaffold(
appBar: AppBar(
title: Text("Scuba Dive"),
actions: <Widget>[
Padding(
padding: const EdgeInsets.all(8.0),
child: Center(child: Text("Sort By")),
),
PopupMenuButton<String>(
icon: Icon(
Icons.sort,
size: 32,
),
onSelected: choiceAction,
itemBuilder: (BuildContext context) {
return Constants.choices.map((String choice) {
return PopupMenuItem<String>(
value: choice,
child: Text(choice),
);
}).toList();
},
)
],
),
body: Container(
constraints: BoxConstraints.expand(),
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/scuba.jpg'),
colorFilter:
ColorFilter.mode(Colors.black26, BlendMode.darken),
fit: BoxFit.cover)),
child: FutureBuilder(
builder: (context, snapshot) {
showData = json.decode(snapshot.data.toString());
if (byName) {
showData.sort();
}
return ListView.builder(
itemBuilder: (BuildContext context, int index) {
return Container(
padding: EdgeInsets.all(8),
margin: EdgeInsets.all(12),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.white70,
),
child: Column(
children: <Widget>[
Row(
children: <Widget>[
ConstrainedBox(
constraints: BoxConstraints(
maxWidth: 150,
maxHeight: 80,
),
child: Image(
image: AssetImage(showData[index]["image"]),
),
),
Flexible(
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment:
CrossAxisAlignment.start,
children: <Widget>[
Text(
showData[index]["name"].toString(),
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold),
),
Text("Rating : " +
showData[index]["rating"]),
],
),
),
),
],
),
],
),
);
},
itemCount: showData == null ? 0 : showData.length,
);
},
future:
DefaultAssetBundle.of(context).loadString("assets/data.json"),
),
),
)
],
);
}
void choiceAction(String choice) {
if (choice == Constants.FirstItem) {
setState(() {
byName = true;
});
} else if (choice == Constants.SecondItem) {
print("Second");
}
}
}
可能是什么原因,我该如何解决?
答案 0 :(得分:1)
错误来自此行:
showData.sort();
因为json.decode
不返回Comparable
。您应该考虑为showData
提供类型(可以是局部变量):
List<Data> showData = List<Data>.from(json.decode(snapshot.data.toString()));