0

我正在尝试在我的定位器中注册一个模型,但是当我在模型中输入参数时我变得不确定。service_locator.dart

import 'package:get_it/get_it.dart';

import '/services/repository_service.dart';
import '/models/addcash.dart';

GetIt locator = GetIt.instance;

void setupLocator() {
  // // Register services
  locator.registerLazySingleton<RepositoryServiceAddCash>(
      () => RepositoryServiceAddCash());

  // Register models
  locator.registerFactory<AddCash>(
      () => AddCash(id, name, amount, data, frequency, isDeleted));
}

参数id, name, amount, data, frequency,isDeleted出现未定义。这是我的模型文件

import 'package:scoped_model/scoped_model.dart';
import 'package:cash_on_hand/service_locator.dart';
import 'package:cash_on_hand/services/repository_service.dart';

import '../data/database.dart';

class AddCash extends Model {
  RepositoryServiceAddCash storageService = locator<RepositoryServiceAddCash>();

  int id;
  String name;
  int amount;
  String date;
  String frequency;
  bool isDeleted;

  AddCash(this.id, this.name, this.amount, this.date, this.frequency,
      this.isDeleted);

  AddCash.fromJson(Map<String, dynamic> json) {
    this.id = json[DatabaseCreator.id];
    this.name = json[DatabaseCreator.name];
    this.amount = json[DatabaseCreator.amount];
    this.date = json[DatabaseCreator.date];
    this.frequency = json[DatabaseCreator.frequency];
    this.isDeleted = json[DatabaseCreator.isDeleted] == 1;
  }
}
4

1 回答 1

1

您可以使用 {} 将构造函数参数更改为可选

AddCash(this.id, this.name, this.amount, this.date, this.frequency, this.isDeleted);

AddCash({this.id, this.name, this.amount, this.date, this.frequency, this.isDeleted});

代码片段

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

GetIt getIt = GetIt.instance;

void main() {
  getIt.registerSingleton<Model>(AddCash(),
      signalsReady: true);

  runApp(MyApp());
}


abstract class Model extends ChangeNotifier {
  int get id;
  String get name;
  int get amount;
  String get date;
  String get frequency;
  bool get isDeleted;
}

class AddCash extends Model {
  int id;
  String name;
  int amount;
  String date;
  String frequency;
  bool isDeleted;

  AddCash({this.id, this.name, this.amount, this.date, this.frequency,
      this.isDeleted});

  /*AddCash.fromJson(Map<String, dynamic> json) {
    this.id = json[DatabaseCreator.id];
    this.name = json[DatabaseCreator.name];
    this.amount = json[DatabaseCreator.amount];
    this.date = json[DatabaseCreator.date];
    this.frequency = json[DatabaseCreator.frequency];
    this.isDeleted = json[DatabaseCreator.isDeleted] == 1;
  }*/
}
于 2019-11-04T09:01:05.403 回答