【问题标题】:Data Received from Laravel API Server Not Shown on Flutter Screen从 Laravel API 服务器接收的数据未显示在 Flutter 屏幕上
【发布时间】:2020-09-17 09:23:07
【问题描述】:

我正在尝试从 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>>'

【问题讨论】:

    标签: php json laravel api flutter


    【解决方案1】:

    问题是FutureBuilder&lt;List&gt; 期待ListgetData 正在返回InternalLinkedHashMap&lt;String, dynamic&gt;。返回对象模型以增加代码可读性并期望相同的对象类,例如FutureBuilder&lt;CustomModel&gt;。检查this

    【讨论】:

    • 为什么 getData() 返回 internalLinkedHashMap 而我已经将它设置为返回 Futute ??
    • 你正在返回这个json.decode(response.body);
    猜你喜欢
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-30
    • 1970-01-01
    • 1970-01-01
    • 2020-11-11
    • 1970-01-01
    相关资源
    最近更新 更多