我是新来的,所以我几乎什么都不知道,但我有一个API,它给了我一个用户.然后,我想要将用户保存在应用程序中,以便我可以使用它来显示信息.现在,我正try 将其作为静态属性保存到类中,但它不起作用.我是不是做错了什么?请帮帮忙好吗?

import 'dart:convert';

import 'package:market/models/offer.dart';

class User{
  String id;
  String firstName;
  String lastName;
  int age;
  bool isVerified;
  String email;
  String phoneNumber;
  String password;
  String description;
  List<Offer> offers;

  // Constructor
  User({required this.id, required this.firstName, required this.lastName,
        required this.age, required this.isVerified, required this.email,
        required this.phoneNumber, required this.password, required this.description,
        required this.offers});

  // Factory constructor to create a User instance from a JSON map
  factory User.fromJson(Map<String, dynamic> json) {
    List<Offer> converted = [];
    for(int i = 0; i < json['offers'].length; i++){
      converted.add(Offer.fromJson(json['offers'][i]));
    }
    return User(
      id: json['id'] as String,
      firstName: json['firstName'] as String,
      lastName: json['lastName'] as String,
      age: json['age'] as int,
      isVerified: json['isVerified'] as bool,
      email: json['email'] as String,
      phoneNumber: json['phoneNumber'] as String,
      password: json['password'] as String,
      description: json['description'] as String,
      offers: converted,

    );
  }

  // Method to convert User instance to a JSON map
  Map<String, dynamic> toJson() {
    return {
      'id': id,
      'firstName': firstName,
      'lastName': lastName,
      'age': age,
      'isVerified': isVerified,
      'email': email,
      'phoneNumber': phoneNumber,
      'password': password,
      'description': description,
      'offers': offers,
    };
  }
}

推荐答案

创建一个UserService(单例)

final class UserService {
  factory UserService() {
    return instance;
  }

  UserService._internal();

  static final UserService instance = UserService._internal();

  User? _user;

  User? get user => _user;

  void setUser(User user) {
    _user = user;
  }

  void clearUser() {
    _user = null;
  }
}

用法示例

void main() async {
  ///
  /// 1. Fetch user data from the server
  /// 2. Save user data to UserService(singleton class)
  /// 3. Use user data from UserService
  /// 4. Clear,Update etc. user data from UserService
  /// 5. DONT USE THESE METHODS IN main() METHOD
  /// I just used it for example
  ///
  ///
  /// 'AsyncSnapshot<User>.nothing()' it's just for example you must use your own api response
  ///
  ///
  final result = const AsyncSnapshot<User>.nothing().data!;

  ///
  ///  User data saved to UserService
  ///
  UserService.instance.setUser(result);

  ///
  ///
  /// You can use UserService everywhere in your app
  ///
  print(UserService.instance.user);
}

.net相关问答推荐

为什么 PropertyInfo.SetValue 在此示例中不起作用以及如何使其起作用?

从删除项目时重新索引的列表中删除项目的最佳算法是什么?

C#.Net 中的可选返回

NonSerialized 属性

根源是什么?

将 DataRowCollection 转换为 IEnumerable

.NET 应用程序的链接器状态(又名请先生,我可以有一个链接器2009 年版)

来自奥尔森时区的 .NET TimeZoneInfo

如何正确停止BackgroundWorker

操作对事务的状态无效错误和事务范围

将接收到的对象转换为 List 或 IEnumerable

如何在我的 C# 程序的面板中运行另一个应用程序?

.NET 中是否有可序列化的通用键/值对类?

MemoryStream.Close() 或 MemoryStream.Dispose()

自定义属性的构造函数何时运行?

一个接口是否应该继承另一个接口

使用 DateTime.ToString() 时获取日期后缀

DataContractSerializer vs XmlSerializer:每个序列化器的优缺点

忽略 LINQ to XML 中的命名空间

是 C# 中的 bool 读/写原子