【问题标题】:In FLutter trying to get JSON had this problem: [ LateInitializationError: Field '_userData@577066488' has not been initialized]在尝试获取 JSON 的 FLutter 中遇到了这个问题:[ LateInitializationError: Field '_userData@577066488' has not been initialized]
【发布时间】:2022-01-12 21:47:12
【问题描述】:

我正在尝试将 JSON 数据从 URL 显示到我的 Flutter 应用程序,但尚未找到任何解决方案。因为我有错误:

[LateInitializationError: 字段 '_userData@577066488' 尚未初始化]

如何在 Flutter 的 ListView 中显示这些数据?

这是我完整的 Flutter 项目:

网址解析:

http://jsonplaceholder.typicode.com/users

Main.dart

import 'package:flutter/material.dart';
import 'json_parse_demo.dart';

void main() {
  runApp(const HomeApp());
}

class HomeApp extends StatelessWidget {
  const HomeApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: JsonParseDemo(),
    );
  }
}

users.dart

// To parse this JSON data, do
//
//     final users = usersFromJson(jsonString);

// ignore_for_file: file_names

import 'dart:convert';

User userFromJson(String str) => User.fromJson(json.decode(str));

String userToJson(User data) => json.encode(data.toJson());

class User {
  User({
    required this.user,
  });

  List<UserElement> user;

  factory User.fromJson(Map<String, dynamic> json) => User(
        user: List<UserElement>.from(
            json["User"].map((x) => UserElement.fromJson(x))),
      );

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

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

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

  factory UserElement.fromJson(Map<String, dynamic> json) => UserElement(
        id: json["id"],
        name: json["name"],
        username: json["username"],
        email: json["email"],
        address: Address.fromJson(json["address"]),
        phone: json["phone"],
        website: json["website"],
        company: Company.fromJson(json["company"]),
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "name": name,
        "username": username,
        "email": email,
        "address": address.toJson(),
        "phone": phone,
        "website": website,
        "company": company.toJson(),
      };
}

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

  String street;
  String suite;
  String city;
  String zipcode;
  Geo geo;

  factory Address.fromJson(Map<String, dynamic> json) => Address(
        street: json["street"],
        suite: json["suite"],
        city: json["city"],
        zipcode: json["zipcode"],
        geo: Geo.fromJson(json["geo"]),
      );

  Map<String, dynamic> toJson() => {
        "street": street,
        "suite": suite,
        "city": city,
        "zipcode": zipcode,
        "geo": geo.toJson(),
      };
}

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

  String lat;
  String lng;

  factory Geo.fromJson(Map<String, dynamic> json) => Geo(
        lat: json["lat"],
        lng: json["lng"],
      );

  Map<String, dynamic> toJson() => {
        "lat": lat,
        "lng": lng,
      };
}

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

  String name;
  String catchPhrase;
  String bs;

  factory Company.fromJson(Map<String, dynamic> json) => Company(
        name: json["name"],
        catchPhrase: json["catchPhrase"],
        bs: json["bs"],
      );

  Map<String, dynamic> toJson() => {
        "name": name,
        "catchPhrase": catchPhrase,
        "bs": bs,
      };
}

servicios.dart

import 'package:http/http.dart' as http;
import 'users.dart';

class Services {
  //
  static Uri uri = Uri.parse('http://jsonplaceholder.typicode.com/users');

  static Future<List<User>> getUsers() async {
    try {
      final response = await http.get(uri);
      if (200 == response.statusCode) {
        final List<User> users = userFromJson(response.body) as List<User>;
        return users;
      } else {
        return <User>[];
      }
    } catch (e) {
      return <User>[];
    }
  }
}

json_parse_demo.dart

// ignore_for_file: unnecessary_null_comparison

import 'package:flutter/material.dart';
import 'users.dart';
import 'servicios.dart';

class JsonParseDemo extends StatefulWidget {
  //
  const JsonParseDemo({Key? key}) : super(key: key);
  @override
  _JsonParseDemoState createState() => _JsonParseDemoState();
}

class _JsonParseDemoState extends State<JsonParseDemo> {
  //
  late List<User> _users;
  // late bool _loading;
  bool _loading = true; 
  
  @override
  void initState() {
    super.initState();
    _loading = true;
    Services.getUsers().then((users) {
      setState(() {
        _users = users;
        _loading = false;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(_loading ? 'Loading...' : 'Users'),
      ),
      body: Container(
        color: Colors.white,
        child: ListView.builder(
          itemCount: null == _users ? 0 : _users.length,
          itemBuilder: (context, index) {
            UserElement user = _users[index] as UserElement;
            return ListTile(
              title: Text(user.name),
              subtitle: Text(user.email),
            );
          },
        ),
      ),
    );
  }
}

【问题讨论】:

    标签: android json flutter dart


    【解决方案1】:

    用异步返回创建一个future函数,然后在initstate(){}中调用它。

    因为 getUser api 调用是一个异步任务。 像这样更改您的代码。

      @override
      void initState() {
        super.initState();
        _loading = true;
       getUserApiCall ();
    }
    
    Future getUserApiCall() async{
    return await Services.getUsers().then((users) {
          setState(() {
            _users = users;
            _loading = false;
          });
        });
    }
    

    如果您遇到任何问题,请告诉我

    【讨论】:

    • 我在 json_parse_demo.dart 中进行了更改,但不幸的是相同的错误:═ 小部件库捕获的异常═════在构建 JsonParseDemo(dirty, state: _JsonParseDemoState#7833b ): LateInitializationError: 字段 '_users@557066488' 尚未初始化。
    猜你喜欢
    • 2021-09-08
    • 1970-01-01
    • 2023-02-24
    • 2021-12-25
    • 1970-01-01
    • 2023-01-21
    • 1970-01-01
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多