在flutter中获取JSON数据将返回NULL

时间:2020-04-06 17:52:26

标签: php json flutter dart

我是陌生的,试图从托管的php文件中获取数据。无论我尝试什么,结果都将返回NULL。我想将所有数据输出到php文件中,而不仅仅是一行。在PHP上,我只需要执行for循环即可获取所有JSON数据。我将如何在Dart中做到这一点?

我的PHP文件-

$sql = "SELECT * FROM user_log";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
    $rows = array();
        while($r = $result->fetch_assoc()) {
        $rows[] = $r;
        }
        $newArray = array_values($rows);
    }
$json_string = json_encode($newArray, true);

echo $json_string;

Dart代码-

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

void main() => runApp(new MyApp());

class MyApp extends StatefulWidget {
   @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
    String name, team;


FetchJSON() async {
    var url = 'https://vettx.app/api/get.php';
    http.Response response = await http.get(url);
    var data = jsonDecode(response.body);
    name = data['0']['user'];
    team = data['0']['team'];
    //print(data.toString());
}

void initState() {
    super.initState();
    FetchJSON();
}

Widget MyUI() {
  return new Container(
      child: new ListView(
        children: <Widget>[
        new Text(
           'Name : $name',
        ),
        new Text(
          'Team : $team',
        ),
      ],
    ),
  );
}


@override
Widget build(BuildContext context) {
  return new MaterialApp(
    home: new Scaffold(
      appBar: new AppBar(
        title: new Text('Get Data'),
      ),
      body: isData
          ? new Center(
        child: new CircularProgressIndicator(),
      )
          : MyUI(),
     ),
   );
  }
}

JSON数据-

{
    "id": "4037",
    "user_id": "1",
    "user": "Ryan Dietz",
    "team": "Manager",
    "action": "email",
    "veh_id": "73366",
    "user_notes": "I am wondering if you have the VIN by chance?",
    "time_stamp": "2020-03-26 20:27:07"
},

链接到JSON示例-

https://vettx.app/api/get.php

1 个答案:

答案 0 :(得分:1)

您的服务器返回一个对象数组,因此您需要解析json并将其存储在数组中。另外,要获取第0个索引,您需要编写array[0],而不是array['0']

代替存储第一个对象属性,您必须从fetchJSON方法返回整个数组:

Future<List> fetchJSON() async {
   var url = 'https://vettx.app/api/get.php';
   http.Response response = await http.get(url);
   var data = jsonDecode(response.body);
   return data;
}

使用FutureBuilder小部件来处理数据的加载和显示,如下所示:

@override
Widget build(BuildContext context) {
  return new MaterialApp(
    home: new Scaffold(
      appBar: new AppBar(
        title: new Text('Get Data'),
      ),
      body: FutureBuilder<List>(
        future: fetchJSON(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              // Success case
              return ListView.builder(
                itemBuilder: (context, index) {
                  return ListTile(
                    title: Text(snapshot.data[index]['user']),
                    subtitle: Text(snapshot.data[index]['team']),
                    trailing: Text(snapshot.data[index]['id']),
                  );
                },
                itemCount: snapshot.data.length,
              );
            }
            // Error case
            return Text('Something went wrong');
          } else {
            // Loading data
            return Center(
              child: CircularProgressIndicator(),
            );
          }
        },
      ),
    ),
  );
}

在上面的代码快照中,数据将是一个对象列表,您可以使用itemBuilder的索引值来遍历该对象。

最后的输出将是:

Output