簡體   English   中英

flutter rest api 得到 json

[英]flutter rest api get json

我剛開始使用 flutter。 我有一個用 nodejs 編寫的 rest api 服務。 下面正在生成 output“result.json”。 我正在嘗試使用 flutter 訪問它。

連接到服務器。 從服務器獲取 json 數據。 但我不能把它帶入卡片。 你能幫助我嗎?

客戶.dart

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

class Customers extends StatefulWidget {
  @override
  _CustomersState createState() => _CustomersState();
}

class _CustomersState extends State<Customers> {
  Future<List<CustomersModel>> _fetchCustomers() async {
    var response = await http.get("http://localhost:3000/customers");
    if (response.statusCode == 200) {
      return (json.decode(response.body))
          .map((e) => CustomersModel.fromJson(e))
          .toList();
    } else {
      throw Exception("not connected ${response.statusCode}");
    }
  }

  @override
  void initState() {
    super.initState();
  }

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Customer list"),
      ),
      body: FutureBuilder(
        future: _fetchCustomers(),
        builder: (BuildContext context,
            AsyncSnapshot<List<CustomersModel>> snapshot) {
          print(snapshot.data);

          if (snapshot.hasData) {
            print(snapshot);
            return ListView.builder(
                //itemCount: snapshot.data.length,
                itemBuilder: (context, index) {
              return ListTile();
            });
          } else {
            return Center(child: CircularProgressIndicator());
          }
        },
      ),
    );
  }
}

客戶型號.dart

import 'dart:convert';

CustomersModel customersModelFromJson(String str) => CustomersModel.fromJson(json.decode(str));

String customersModelToJson(CustomersModel data) => json.encode(data.toJson());

class CustomersModel {
    CustomersModel({
        this.result,
    });

    List<Result> result;

    factory CustomersModel.fromJson(Map<String, dynamic> json) => CustomersModel(
        result: List<Result>.from(json["result"].map((x) => Result.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "result": List<dynamic>.from(result.map((x) => x.toJson())),
    };
}

class Result {
    Result({
        this.id,
        this.customerName,
        this.customerLastname,
    });

    int id;
    String customerName;
    String customerLastname;

    factory Result.fromJson(Map<String, dynamic> json) => Result(
        id: json["id"],
        customerName: json["customer_name"],
        customerLastname: json["customer_lastname"],
    );

    Map<String, dynamic> toJson() => {
        "id": id,
        "customer_name": customerName,
        "customer_lastname": customerLastname,
    };
}

結果.json

{
    "result": [
        {
            "id": 1,
            "customer_name": "John",
            "customer_lastname": "simon"
        },
        {
            "id": 2,
            "customer_name": "peter",
            "customer_lastname": "bratt"
        }
    ]
}

_fetchCustomer()更改為以下

Future<CustomersModel> _fetchCustomers() async { // this line
  var response = await http.get("http://localhost:3000/customers");
  if (response.statusCode == 200) {
    return customersModelFromJson(response.body); // this line
  } else {
    throw Exception("not connected ${response.statusCode}");
  }
}

並使用以下更改您的FutureBuilder

FutureBuilder(
    future: _fetchCustomers(),
    builder: (BuildContext context,
        AsyncSnapshot<CustomersModel> snapshot) { // this line
      print(snapshot.data);

      if (snapshot.hasData) {
        print(snapshot);
        return ListView.builder(
            itemCount: snapshot.data.result.length, // this line
            itemBuilder: (context, index) {
          return ListTile();
        });
      } else {
        return Center(child: CircularProgressIndicator());
      }
    },
  )

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM