php - 从 Laravel API 服务器接收的数据未显示在 Flutter 屏幕上
问题描述
我正在尝试从 Laravel php 服务器接收数据,并将其显示在 Flutter Login 屏幕上,该屏幕在成功登录后定向到 Dashboard,但没有显示数据,只有加载图标继续加载在屏幕上。
下面是登录代码:
class DashboardState extends State<Dashboard>{
DataBaseHelper dataBaseHelper = new DataBaseHelper();
@override
Widget build(BuildContext context) {
// TODO: implement build
return MaterialApp(
title: 'Dashboard',
home: Scaffold(
appBar: AppBar(
title: Text('Dashboard'),
),
floatingActionButton: FloatingActionButton(
onPressed: ()=>
Navigator.of(context).push(new MaterialPageRoute(
builder: (BuildContext context)=> new AddData(),
))
,
child: Icon(Icons.add),
),
body: Container(
child: FutureBuilder<List>(
future: dataBaseHelper.getData(),
builder: (context, snapshot){
if(snapshot.hasError) print(snapshot.error);
return snapshot.hasData
? new ItemList(list: snapshot.data)
: new Center(child: CircularProgressIndicator(),);
},
)
),
),
);
}
}
这是 getData() 函数,它从服务器接收数据并位于 databasehelper 中:
Future<List> getData() async{
final prefs = await SharedPreferences.getInstance();
final key = 'token';
final value = prefs.get(key) ?? 0;
var url = '$serverUrl/cars/';
final response = await http.get(url,
headers: {
'Accept':'application/json',
'Authorization' : 'Bearer $value'
},
);
return json.decode(response.body);
}
注意当用户登录并转到仪表板时,我在控制台上收到以下消息:
I/flutter ( 9962): type '_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'FutureOr<List<dynamic>>'
解决方案
问题是FutureBuilder<List>
期待List
并且getData
正在返回InternalLinkedHashMap<String, dynamic>
。返回对象模型以增加代码可读性并期望相同的对象类,例如FutureBuilder<CustomModel>
. 检查这个。