【问题标题】:ChangeNotifier Model - How to use fromMap()?ChangeNotifier 模型 - 如何使用 fromMap()?
【发布时间】:2021-05-26 17:36:30
【问题描述】:

我有一个类扩展 ChangeNotifier 像这样

import 'package:flutter/foundation.dart';

class Person extends ChangeNotifier {
  int _age = 0;

  int get age => _age;

  set age(int value) {
    _age = value;
    notifyListeners();
  }

  factory Person.fromMap(Map<String, dynamic> obj) => Person(
        age: obj["Age"],
      );
}

但在添加fromMap 方法时出现此错误

The class 'Person' doesn't have a default constructor.
Try using one of the named constructors defined in 'Person'.

知道如何纠正这个问题吗?

我试过

class Person extends ChangeNotifier {

  Person();

  int _age = 0;

  int get age => _age;

  set age(int value) {
    _age = value;
    notifyListeners();
  }

  factory Person.fromMap(Map<String, dynamic> obj) => Person(
        age: obj["Age"],
      );
}

然后被告知

The named parameter 'age' isn't defined.
Try correcting the name to an existing named parameter's name, or defining a named parameter with the name 'age'

【问题讨论】:

    标签: flutter dart


    【解决方案1】:

    您必须创建一个以年龄为参数的命名构造函数。

    class Person extends ChangeNotifier {
    
      int _age = 0;
    
      Person({int age}) : this._age = age;
    
      // Rest of your code
    }
    

    您可以在此处阅读更多关于构造函数的信息Dart Language Tour

    【讨论】:

    • 谢谢,你能解释一下这部分是做什么的吗? Person({int age}) : this._age = age; 通常我会使用 Person({this.age});
    • @totalitarian 你没有名为age 的公共成员变量,你有一个私有变量_age。所以你在Person({int age}) 中引入了一个本地参数/变量,你可以在那里放任何参数名称,比如Person({int foo})。然后你想将你在本地参数中收到的值分配给你的私人成员。
    • @totalitarian 我在一行中简化了成员变量赋值。和写Person({int age}) { this._age = age;}一样
    猜你喜欢
    • 2020-02-07
    • 1970-01-01
    • 2019-12-24
    • 2020-09-05
    • 2020-09-17
    • 2019-11-18
    • 1970-01-01
    • 2022-10-30
    • 2019-12-11
    相关资源
    最近更新 更多