Only static members can be accessed in initializer. Dart2.0
Asked Answered
A

1

5

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});

}
Amylopsin answered 16/8, 2018 at 8:42 Comment(0)
M
6

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.

Marks answered 16/8, 2018 at 9:38 Comment(3)
SO in this case i have to use static for that? And if i want to create or typed any widget before creating body container . How to do that?Amylopsin
You can move the initialization to the constructor body, there it's already allowed to reference this.. If you want to make the field final it's more complicated.Epaminondas
Thank you so much.Amylopsin

© 2022 - 2024 — McMap. All rights reserved.