【问题标题】:flutter rest api get json颤振休息api获取json
【发布时间】:2021-05-16 22:38:40
【问题描述】:

我刚开始使用颤振。我有一个用 nodejs 编写的 rest api 服务。下面正在生成输出“result.json”。我正在尝试通过颤振访问它。

连接到服务器。 从服务器获取 json 数据。 但我不能把它带入卡片。你能帮我吗?

Customers.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());
          }
        },
      ),
    );
  }
}

CustomersModel.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,
    };
}

Result.json

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

【问题讨论】:

  • But I cannot take this into card 没有得到这个

标签: json api flutter


【解决方案1】:

用下面的方式更改 _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());
      }
    },
  )

【讨论】:

    猜你喜欢
    • 2020-03-19
    • 2021-04-23
    • 2022-08-18
    • 2020-05-02
    • 2021-03-17
    • 2021-03-21
    • 1970-01-01
    • 2021-07-22
    • 2021-01-26
    相关资源
    最近更新 更多