在初始化器中只能访问静态成员。 Dart2.0

时间:2018-08-16 08:42:30

标签: dart flutter dart-2

我在有状态小部件中使用银行清单。使用pageState

将列表传递到List<Bank> bankLists = this.widget.bankLists;

队列1。为什么在gradientcolor: gradientBankCard("FFB74093","FFB74093"))出现错误,提示只能在初始化程序中访问静态成员?

队列2。如何将const数据传递给gradientBankCard方法。例如,我想将Color.fromRGBO(220, 132, 58, 1.0)传递给给出错误的参数。 我

List<Bank> bankLists = [
 Bank(
    id: "1",
    name: "B1",
    loanAmount: "₹ 250000",
    emi: "₹11732",
    intrest_rate: "11.69 % ",
    processing_fee: "1.29 %",
    tenure: "2 years",
    gradientcolor: gradientBankCard('#e48634', '#e48634')), // //Error : Only static members can be accessed in initializers
 Bank(
    id: "2",
    name: "B2",
    loanAmount: "₹ 250000",
    emi: "₹11732",
    intrest_rate: "11.69 % ",
    processing_fee: "1.29 %",
    tenure: "2 years",
    gradientcolor: gradientBankCard('#e48634', '#e48634')) //Error : Only static members can be accessed in initializers
];

现在我在列表屏幕中使用。

LinearGradient gradientBankCard(String startColor, String  endColor){

return LinearGradient(
    begin: Alignment.topLeft,
    end: Alignment.bottomRight,
    colors: [Color(hexToInt(startColor)),Color(hexToInt(endColor))]
);
}

Bank Model.dart

import 'package:flutter/material.dart';



class Bank {
  final String id;
  final String name;
  final String loanAmount;
  final String emi;
  final String intrest_rate;
  final String processing_fee;
  final String tenure;
  LinearGradient gradientcolor;

  Bank({this.id, this.name, this.loanAmount, this.emi, this.intrest_rate,
      this.processing_fee, this.tenure,this.gradientcolor});

}

1 个答案:

答案 0 :(得分:4)

代码

gradientcolor: gradientBankCard('#e48634', '#e48634')),

在类完全初始化之前执行。 字段的初始化器

List<Bank> bankLists = [...];

是在执行超级构造函数之前执行的,此时,不允许对this.的显式或隐式访问,因为这将允许访问未完全初始化的状态。

如果您更改

LinearGradient gradientBankCard(String startColor, String  endColor){ ...

static LinearGradient gradientBankCard(String startColor, String  endColor){

然后无法访问this.,因此很安全。