用dart获取json数据的问题

时间:2019-04-02 02:25:24

标签: json api http dart flutter

我在dart中使用代码获取api数据。 代码没有显示任何错误,也没有响应数据。

API链接:https://jsonplaceholder.typicode.com/users

环境:   sdk: ">=2.1.0 <3.0.0"

依赖性:   扑:     SDK:颤振   http:任何

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() async {
    List _data =  await getJSON();
    print("hello world ");
    runApp(
    new MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Jason Pddarsin"),
          backgroundColor: Colors.orange,
          centerTitle: true,
        ),

        body: ListView.builder(
            itemCount: _data.length,
            itemBuilder: (BuildContext context, int pos) {
              return Column(
                children: <Widget>[
                  Divider(
                    height: 5.5,
                  ),
                  Text(_data[pos]["name"]),
                ],
              );
            }),
      ),
     ),
    );
    }

    Future<List> getJSON() async {
    String apiUrl = "https://jsonplaceholder.typicode.com/users";
    http.Response response = await http.get(apiUrl);
    return json.decode(response.body);
}    

如果我直接使用该代码移动白屏,我将使用一个简单的应用程序来运行materialapp,然后将其添加到我的代码中,并且不会显示任何数据。

1 个答案:

答案 0 :(得分:0)

我刚刚将您的代码复制并粘贴到一个全新的flutter项目中,效果很好。您收到任何错误消息吗?您说过将它放在另一个MaterialApp中?如果是这种情况,请尝试直接从您的主体而不是在MaterialApp内部调用它。  enter image description here