我得到一个未处理的异常:类型'Null'不是类型'FutureOR的子类型
API需要太多的时间来加载,有时加载得非常快。我提供了下面的代码。
Future<List<dynamic>> getSubjects() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var token = prefs.getString('token');
var result = await http.get(
Uri.parse("xxxxxxxxxxxx"),
headers: {
'Accept': 'application/json',
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': "Bearer $token",
});
return jsonDecode(result.body)['result'];
}
未来建筑代码
Padding(
padding: const EdgeInsets.all(18.0),
child: FutureBuilder(
future: getSubjects(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return ListView.builder(
shrinkWrap: true,
itemCount: snapshot.data?.length,
itemBuilder: (BuildContext context, int index) {
return Padding(
padding: const EdgeInsets.all(5.0),
child: Container(
decoration: BoxDecoration(
image: const DecorationImage(
image: AssetImage('assets/bg.png'),
fit: BoxFit.cover,
),
color: Colors.amber[50],
borderRadius: BorderRadius.circular(10.0),
boxShadow: const [
BoxShadow(
color: Colors.grey,
blurRadius: 2.0,
offset: Offset(2.0, 2.0))
],
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
crossAxisAlignment: CrossAxisAlignment.start,
children: [
ListTile(
title: Text(
snapshot.data[index]['subject_name']
.toString(),
style: const TextStyle(color: Colors.white),
),
trailing: Row(
mainAxisSize: MainAxisSize.min,
children: [
Icon((Icons.book),
color: Colors.amber.shade900),
const SizedBox(
width: 10.00,
),
],
),
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) =>
GiveFeedbackScreen(
subjectId: snapshot.data[index]
['subject_id'],
subjectName: snapshot.data[index]
['subject_name'],
feedbackId: widget.id,
),
),
);
},
),
],
),
),
),
);
},
);
} else {
return Center(
child: LinearProgressIndicator(
backgroundColor: Colors.amber[500]),
);
}
},
),
),
删除'Content-Type':'application/x-wew-form-urlencoded',
…不确定get请求是否需要此内容类型
将您的函数编写为Future
它会解决你的问题
我认为最好接受来自未来的null。尝试喜欢
Future<List<dynamic>?> getSubjects(){...}
而当
FutureBuilder<List<dynamic>?>(
builder: (context, snapshot) {
if(snapshot.hasData){}