【发布时间】:2020-07-18 19:26:51
【问题描述】:
我是 Flutter 的新手,并试图从托管的 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;
飞镖代码 -
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
【问题讨论】:
-
您的 json 未返回列表,因此请尝试使用 data['user] 访问用户。
-
是的,不走运,如果您查看示例 php 链接,json 数据的父级别为 [0]
-
http.get(url).then((response){ var data = jsonDecode(response.body); name = data['0']['user']; team = data[' 0']['团队']; });试试这个
-
如果我 print(data.toString()); 仍然返回 NULL;它将所有数据输出到日志中,这真的让我感到困惑,为什么它将 NULL 返回到屏幕。
-
从零附近删除单引号 (')。数据[0]['用户']