Флаттер: json данные не отображаются в будущем компоновщике при запросе http get - PullRequest
0 голосов
/ 18 февраля 2020

Я пытаюсь отобразить элементы из json http запроса на получение. Но он ничего не отображает.

Это функция запроса

  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

Это мой json файл

А это код php для извлечения данных из базы данных и создания формата json

$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 голосов
/ 19 февраля 2020

Вы можете скопировать вставленный полный код ниже
Вы можете увидеть 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),
      ),
    );
  }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...