我的snapshot.data为空。当我打印响应时,它显示检索到的数据。但是快照.data仍然为空。请帮忙。
Future _getUsers() async {
var data = await http.post("http://10.0.2.2/Flutter/abreport.php", body: {
{
"date": mydt,
});
var jsonData = json.decode(data.body); //edited
print(jsonData); // the data is printing here
return jsonData;
}
}
FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
debugPrint(snapshot.data);
if (snapshot.data == null) {
return Container(
child: Center(
child:Text("no data"),
)
);
} else {
//some code
}
)
答案 0 :(得分:0)
您应该使用FutureBuilder
文档中提供的格式。您无需检查未来的状态,因此在首次构建FutureBuilder
时,它将显示"no data"
。您尚未实现else
分支,因此,在拥有数据时,您的构建可能仍将无法刷新。请尝试以下代码:
FutureBuilder(
future: _getUsers(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.data == null) {
return Text('no data');
} else {
return Text('data present');
}
} else if (snapshot.connectionState == ConnectionState.error) {
return Text('Error'); // error
} else {
return CircularProgressIndicator(); // loading
}
}
)
答案 1 :(得分:0)
由于我看不到完整的代码,因此我假设您在FutureBuilder中接收到json数据后,错误地解析了它。以下是与您正在执行的操作类似的示例。此示例检索Date json数据并使用FutureBuilder显示,
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
MyAppState createState() => MyAppState();
}
class MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.only(left: 10.0, right: 10.0),
child: FutureBuilder(
future: _getDate(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Text('Date: ' + snapshot.data['date']
+ '\nMilliseconds Since Epoch: ' + snapshot.data['milliseconds_since_epoch'].toString()
+ '\nTime: ' + snapshot.data['time'],
style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold, color: Colors.grey));
} else {
return Center(child: CircularProgressIndicator());
}
},
))
]))));
}
Future _getDate() async {
var data = await http.post("http://date.jsontest.com/");
var jsonData = json.decode(data.body);
print(jsonData);
return jsonData;
}
}
测试屏幕截图:
希望这会有所帮助。
答案 2 :(得分:0)
使用 Flutter 2.2,这个返回错误
builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
if (snapshot.hasData) {
return Text(snapshot.data,);
Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
return Text(snapshot.data,);
但是这个没有
builder: (BuildContext context, AsyncSnapshot snapshot) {
当类似的事情发生时,取类型“var”而不是“String”或其他不可为空的类型。 (如果不是 Flutter,编译器会做?)