问题
I am using banklist in stateful widget. passing list to pageState
using List<Bank> bankLists = this.widget.bankLists;
Que 1. Why I am getting error at gradientcolor: gradientBankCard("FFB74093","FFB74093"))
that only static members can be accessed in initializer?
Que 2. How to pass const Data to gradientBankCard
method . for Example I want to pass Color.fromRGBO(220, 132, 58, 1.0)
to Arguments that gives error to.
I
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
];
Now I am using in my listing screen .
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:
The code
gradientcolor: gradientBankCard('#e48634', '#e48634')),
is executed before the class is fully initialized. Initializers of fields like
List<Bank> bankLists = [...];
is executed before the super constructors are executed and at that point explicit or implict access to this.
is not allowed because it would allow access to incompletely initialized state.
If you change
LinearGradient gradientBankCard(String startColor, String endColor){ ...
to
static LinearGradient gradientBankCard(String startColor, String endColor){
then there is no way to access this.
and is therefore safe.
来源:https://stackoverflow.com/questions/51873003/only-static-members-can-be-accessed-in-initializer-dart2-0