Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access one class method from another class in dart?

Tags:

flutter

dart

I'm new to dart. Currently, working on a mobile app through flutter. I have a Helper class which has some common methods which I've planned throughout the app. I've included that Helper class in another class. But, can't able to fig. out how to access its methods.

My commom Helper class code:

import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class Helper {

  Map userDetails = {};
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  // --- Method for getting user details from shared preference ---
  Future<Map>getUserDetailsFromSharedPreference () async {
    try {
      final SharedPreferences prefs = await _prefs;

      if(prefs.getString('user') != null) {
        this.userDetails = json.decode(prefs.getString('user'));
      } else {
        print('Shared preference has no data');
      }

    } catch (e){
      print('Exception caught at getUserDetails method');
      print(e.toString());
    }

    return this.userDetails;
  }

}

Here is my main program code where I've included the Helper class & trying to access it's getUserDetailsFromSharedPreference (). In this case, I'm getting an error like Only static memebers can be accessed in initializers. I also tried to extends Helper class in UserProfile class. But, there also I'm getting a different kind of errors. Can't able to identify how to do this thing.

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

class UserProfile extends StatefulWidget {
    @override
    UserProfileState createState() => new UserProfileState();
}

class UserProfileState extends State<UserProfile> {
    Helper helper = new Helper();
    var userData = helper.getUserDetailsFromSharedPreference();
}

@Günter Zöchbauer I've made my Helper.dart file like this as you've suggested -

import 'dart:async';
import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';

class Helper {

  Map userDetails = {};
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();

  static Helper _instance;
  factory Helper() => _instance ??= new Helper._();

  Helper._();

  // --- Method for getting user details from shared preference ---
  Future<Map>getUserDetailsFromSharedPreference () async {
    try {
      final SharedPreferences prefs = await _prefs;

      if(prefs.getString('user') != null) {
        this.userDetails = json.decode(prefs.getString('user'));
      } else {
        print('Shared preference has no data');
      }

    } catch (e){
      print('Exception caught at getUserDetails method');
      print(e.toString());
    }

    return this.userDetails;
  }

}

Now, in my tryint to access that getUserDetailsFromSharedPreference() method I'm getting the same error Only static memebers can be accessed in initializers .

enter image description here

like image 422
Suresh Avatar asked May 08 '18 07:05

Suresh


People also ask

How do you call a method from another class in Flutter Dart?

We can access it easily just like below. Show activity on this post. Show activity on this post. Import HomePage class in DetailsPage and make a new instance out of it, then call the method you want if it's a public one.

How do you access the class in darts?

A class's attributes and functions can be accessed through the object. Use the '. ' dot notation (called as the period) to access the data members of a class.


Video Answer


1 Answers

You could ensure a singleton instance of the class using a public factory constructor with a private regular constructor:

class Helper {
  static Helper _instance;
  factory Helper() => _instance ??= new Helper._();

  Helper._();

  ...
}

If you call new Helper(), you'll always get the same instance.

You need to import the file that contains class Helper {} everywhere where you want to use it.

??= means new Helper._() is only executed when _instance is null and if it is executed the result will be assigned to _instance before it is returned to the caller.

update

getUserDetailsFromSharedPreference is async and can therefore not be used in the way you use it, at least it will not lead to the expected result. getUserDetailsFromSharedPreference returns a Future that provides the result when the Future completes.

class UserProfileState extends State<UserProfile> {
    Helper helper = new Helper();
    Future<Map> _userData; // this with ??= of the next line is to prevent `getUserDetailsFromSharedPreference` to be called more than once 
    Future<Map> get userData => _userData ??= helper.getUserDetailsFromSharedPreference();
}

If you need to access userData you need to mark the method where you do with async and use await to get the result.

  foo() async {
    var ud = await userData;
    print(ud);
  }
like image 75
Günter Zöchbauer Avatar answered Oct 12 '22 11:10

Günter Zöchbauer