【问题标题】:why json isn't doing anything flutter?为什么json没有做任何事情?
【发布时间】:2021-12-20 11:52:23
【问题描述】:
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

class Datafromapi extends StatefulWidget {
  const Datafromapi({Key? key}) : super(key: key);

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

class _DatafromapiState extends State<Datafromapi> {
  Future<List<User>> getUserData() async {
    var data = await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
    var jsonData = jsonDecode(data.body); //the body here means the string of this
    //variable call response

    List<User> users = []; //the User here means the class model we create and
    //the list here is because later json is going to put the string here

    for (var u in jsonData) {
      User user = User(u['name'], u['email'], u['username']);
      users.add(user);
    }
    print(users.length);
    return users;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text('json getting data'),
        ),
        body: Container(
          child: FutureBuilder(
            future: getUserData(),
            builder:(BuildContext context, AsyncSnapshot snapshot) {
              if (snapshot.data == null) {
                return Container(child: Center(
                    child: Text('loading....')
                ));
              } else {
                return ListView.builder(itemCount: snapshot.data.length
                    ,itemBuilder: (BuildContext context, index) {
                      return ListTile(
                        title: Text(snapshot.data[index].name),
                      );
                    });
              }
            }),),);
  }

}

class User {
 final int id;
 final String name;
 final String username;

 User(this.id,this.name,this.username);
} //the class model

这是我的代码 基本上我想构建一个从 HTTP 获取数据然后在列表视图中打印但 json 没有运行的应用程序我不知道为什么它不能获取数据 谁能帮忙

我已经尝试了几个代码,但它无法工作。我想也许是 getuserdata 有问题任何人都可以帮助我

【问题讨论】:

  • 你有什么错误吗?请更新您的问题并添加您遇到的jsonData 值或错误。
  • 你检查data.statusCode是200了吗?

标签: json flutter http dart


【解决方案1】:

如果您使用fromJsontoJson 创建UserListModel,这将是一个救命稻草。 您可以借助此 url 并稍作修改来完成此操作

当您使用 https://jsonplaceholder.typicode.com/users 这个 API 时。我们的用户模型可以如下:

class UserListModel {
  List<User> user;

  UserListModel({this.user});

  UserListModel.fromJson(List<dynamic> json) {
    if (json != null) {
      user = [];
      json.forEach((v) {
        user.add(new User.fromJson(v));
      });
    }
  }

  List<dynamic> toJson() {
    return this.user.map((v) => v.toJson()).toList();
  }
}

class User {
  int id;
  String name;
  String username;
  String email;
  Address address;
  String phone;
  String website;
  Company company;

  User(
      {this.id,
      this.name,
      this.username,
      this.email,
      this.address,
      this.phone,
      this.website,
      this.company});

  User.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    name = json['name'];
    username = json['username'];
    email = json['email'];
    address =
        json['address'] != null ? new Address.fromJson(json['address']) : null;
    phone = json['phone'];
    website = json['website'];
    company =
        json['company'] != null ? new Company.fromJson(json['company']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['name'] = this.name;
    data['username'] = this.username;
    data['email'] = this.email;
    if (this.address != null) {
      data['address'] = this.address.toJson();
    }
    data['phone'] = this.phone;
    data['website'] = this.website;
    if (this.company != null) {
      data['company'] = this.company.toJson();
    }
    return data;
  }
}

class Address {
  String street;
  String suite;
  String city;
  String zipcode;
  Geo geo;

  Address({this.street, this.suite, this.city, this.zipcode, this.geo});

  Address.fromJson(Map<String, dynamic> json) {
    street = json['street'];
    suite = json['suite'];
    city = json['city'];
    zipcode = json['zipcode'];
    geo = json['geo'] != null ? new Geo.fromJson(json['geo']) : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['street'] = this.street;
    data['suite'] = this.suite;
    data['city'] = this.city;
    data['zipcode'] = this.zipcode;
    if (this.geo != null) {
      data['geo'] = this.geo.toJson();
    }
    return data;
  }
}

class Geo {
  String lat;
  String lng;

  Geo({this.lat, this.lng});

  Geo.fromJson(Map<String, dynamic> json) {
    lat = json['lat'];
    lng = json['lng'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['lat'] = this.lat;
    data['lng'] = this.lng;
    return data;
  }
}

class Company {
  String name;
  String catchPhrase;
  String bs;

  Company({this.name, this.catchPhrase, this.bs});

  Company.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    catchPhrase = json['catchPhrase'];
    bs = json['bs'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['name'] = this.name;
    data['catchPhrase'] = this.catchPhrase;
    data['bs'] = this.bs;
    return data;
  }
}

然后在 API 调用之后,将其绑定到此模型

Future<UserListModel> getUserData() async {
  var data = await http.get(Uri.https('jsonplaceholder.typicode.com', 'users'));
  return UserListModel.fromJson(jsonDecode(data.body));
}

ListView 中使用它,如下所示

 

 ListView.builder(itemCount: snapshot.data.user.length,
   itemBuilder: (BuildContext context, index) {
      return ListTile(
        title: Text(snapshot.data.user[index].name),
      );
 });

【讨论】:

    猜你喜欢
    • 2021-08-11
    • 2011-07-25
    • 2015-06-30
    • 2023-04-06
    • 2021-04-10
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多