Flutter:json数据未在http get请求的将来的构建器中显示

时间:2020-02-18 20:37:58

标签: json http flutter get

我正在尝试显示来自json http get请求的项目。但是它什么也没显示。

这是请求功能

  Future<List<Products>> _getProducts() async{
    var data = await http.get("http://orangecitycafe.in/app_configs/products_display.php");
    var jsonData = json.decode(data.body);
    List<Products> products = [];

    for (var p in jsonData){
      Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
      price: p["product_price"],image: p["product_image"]);
      products.add(product);
    }
    print(products);
    return products;
  }

注意:这是我自定义创建的json文件

This is my json file

这是用于从数据库中获取数据并创建json格式的php代码

$sql = "SELECT * FROM $products_table";
$result = mysqli_query($conn,$sql);
$db_data = array();

if(mysqli_num_rows($result)){
    while($row = mysqli_fetch_array($result)){
        $db_data[] = $row;
    }
    echo json_encode($db_data);
}

这是Future Builder的用户界面

body: 
      Container(
        child: FutureBuilder(
          future: _getProducts(),
          builder: (BuildContext context, AsyncSnapshot snapshot){

            if(snapshot.data == null){
              return Container(
                child: Center(
                  child: CircularProgressIndicator(),
                ),
              );
            }
            else{
            return ListView.builder(
              itemCount: snapshot.data.length,
              itemBuilder: (BuildContext context, int index){
                return ListTile(
                  title: Text(snapshot.data[index].price),
                );
              },
            );
            }
          },
        ),
      )

我不知道错误在哪里。是由于我的自定义json文件引起的,还是我可能会错过一些东西。

1 个答案:

答案 0 :(得分:0)

您可以在下面复制粘贴运行完整代码
您可以看到完整代码的Products

代码片段以解析json字符串

Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  return products;
}

工作演示

enter image description here

完整代码

import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
// To parse this JSON data, do
//
//     final products = productsFromJson(jsonString);

import 'dart:convert';

List<Products> productsFromJson(String str) =>
    List<Products>.from(json.decode(str).map((x) => Products.fromJson(x)));

String productsToJson(List<Products> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Products {
  String the0;
  String the1;
  String the2;
  String the3;
  String the4;
  DateTime the5;
  String productId;
  String categId;
  String productName;
  String productPrice;
  String productImage;
  DateTime addedDate;

  Products({
    this.the0,
    this.the1,
    this.the2,
    this.the3,
    this.the4,
    this.the5,
    this.productId,
    this.categId,
    this.productName,
    this.productPrice,
    this.productImage,
    this.addedDate,
  });

  factory Products.fromJson(Map<String, dynamic> json) => Products(
        the0: json["0"],
        the1: json["1"],
        the2: json["2"],
        the3: json["3"],
        the4: json["4"],
        the5: DateTime.parse(json["5"]),
        productId: json["product_id"],
        categId: json["categ_id"],
        productName: json["product_name"],
        productPrice: json["product_price"],
        productImage: json["product_image"],
        addedDate: DateTime.parse(json["added_date"]),
      );

  Map<String, dynamic> toJson() => {
        "0": the0,
        "1": the1,
        "2": the2,
        "3": the3,
        "4": the4,
        "5": the5.toIso8601String(),
        "product_id": productId,
        "categ_id": categId,
        "product_name": productName,
        "product_price": productPrice,
        "product_image": productImage,
        "added_date": addedDate.toIso8601String(),
      };
}

Future<List<Products>> _getProducts() async {
  var data = await http
      .get("http://orangecitycafe.in/app_configs/products_display.php");
  var jsonData = json.decode(data.body);
  List<Products> products = [];
  products = productsFromJson(data.body);

  /*for (var p in jsonData){
    Products product = Products(index: p["index"], id: p["product_id"], name: p["product_name"],
        price: p["product_price"],image: p["product_image"]);
    products.add(product);
  }
  print(products);*/
  return products;
}

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Expanded(
              child: FutureBuilder(
                future: _getProducts(),
                builder: (BuildContext context, AsyncSnapshot snapshot) {
                  if (snapshot.data == null) {
                    return Container(
                      child: Center(
                        child: CircularProgressIndicator(),
                      ),
                    );
                  } else {
                    return ListView.builder(
                      itemCount: snapshot.data.length,
                      itemBuilder: (BuildContext context, int index) {
                        return ListTile(
                          title: Text(snapshot.data[index].productName),
                        );
                      },
                    );
                  }
                },
              ),
            ),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}