0

I am very new to flutter and dart and trying to use singleton instance for global state(?). which is company info that gets from backend server. When flutter app starts, send request to the server and get a response and build a singleton instance based on the response. So I created class

class Company {
  static final Company _instance = new Company._internal();

  factory Company() {
    return _instance;
  }

  @protected
  String name;
  @protected
  String intro;

  String get companyName => name;
  String get companyIntro => intro;

  void setCompany(String name, String intro) {
    name = name;
    intro = intro;
  }

  Company._internal();
}

in main.dart

// companyResult is the response from server
final String companyName = companyResult["name"];
final String companyIntro = companyResult["intro"];

// create singleton instance
var company = Company();
// set company info
company.setCompany(companyName, companyIntro);

// cheking
print(company.companyName)

prints null

What am I doing wrong?

2
  • 1
    What is the error that you got or what is the result that ou got? Commented Apr 29, 2020 at 23:32
  • I think setComany is not setting a value. Printing company's property after calling setCompany prints null. Commented Apr 29, 2020 at 23:33

1 Answer 1

1

Singletons are better avoided, I would recommend that you use Provider instead and inject a simple object reference on your widget tree, so you can grab that reference whenever you want.

The reason your example prints null is because you are wrongly referencing your variables on setCompany(), the variables name and intro are all the same variable, you are changing the variables internal to the function, not the class variables, in order to fix it change it to:

void setCompany(String name, String intro) {
  this.name = name;
  this.intro = intro;
}

Also, I would suggest you name your variables _name and _intro, as there's no sense in having a get for a variable that's no private.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for your answer. I will look into Provider.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.