Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

2 positional argument(s) expected, but 0 found bypass via another class

I created a class where I write a theme model:

import 'package:flutter/material.dart';
import 'theme_preference.dart';

class ThemeModel extends ChangeNotifier {
  bool _isDark;
  ThemePreferences _preferences;
  bool get isDark => _isDark;

  ThemeModel(this._preferences, this._isDark) {
    _isDark = false;
    _preferences = ThemePreferences();
    getPreferences();
  }

  set isDark(bool value) {
    _isDark = value;
    _preferences.setTheme(value);
    notifyListeners();
  }

  getPreferences() async {
    _isDark = await _preferences.getTheme();
    notifyListeners();
  }
}

to use the change I had to add create: (_) => ThemeModel(this._preferences, this._isDark), in the main class. But when I do it so, I get an error like this: The getter '_isDark' isn't defined for the type '_ToDoState'. I can´t initialise the variables in the main class so my question is, if there is a way that I can cast these thinks in the other class where I initialised it?

By the way I am following this tutorial:
https://www.flutterant.com/switching-themes-in-flutter-apps/

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The main issue here is that ThemeModel is changed from the example in the article in an attempt to solve problems related to null-safety (the article is written before null-safety was introduced). Instead of the current ThemeModel it should be changed to:

class ThemeModel extends ChangeNotifier {
  bool _isDark = _false;
  ThemePreferences _preferences = ThemePreferences();
  bool get isDark => _isDark;

  ThemeModel() {
    getPreferences();
  }

  set isDark(bool value) {
    _isDark = value;
    _preferences.setTheme(value);
    notifyListeners();
  }

  void getPreferences() async {
    _isDark = await _preferences.getTheme();
    notifyListeners();
  }
}

Since the example is not made for ThemeModel to take any arguments.

Objects in Dart are created in two phases and all non-nullable non-late variable must have a value before the constructor body is executed. By changing the code like I have done, the variables _isDark and _preferences gets initial values before the constructor body is executing getPreferences();.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading