xenos92
xenos92

Reputation: 361

Flutter call different types in a function

I can't find the answer on the internet. I have a function which loads me a json file according to parameter. The parameter is a class which contains the form of my page which I call FormHome. I have another form page that needs to call this json loader function. The class is therefore called FormProfil.

in my function I allow the type of type FormHome. How can I also authorize the FormProfil type?

static Future<List<User>> load(FormHome formData) async
  {
      if(formData.username== AppConfig.VALUE){
        try{
          List _jsonUsers = await loadJsonParsed("myfile.json");
          return UsersList.fromJson(_jsonUsers ).user;
        }
        catch(Exception){
          throw MyException.jsonUsersError();
        }
      }
      else{
        throw MyException.Error();
      }
  }

My class FormHome :

class FormHome {
  String username;
  String age;
  String gender;

  FormHome ({
    this.username,
    this.age,
    this.gender
  });

  Map<String, dynamic> toJson() => {
    'username': username.toString(),
    'age': age.toString(),
    'gender': gender.toString()
  };

  @override
  String toString() {
    return '{ '
        '${this.username}, '
        '${this.age}, '
        '${this.gender}, '
    '}';
  }
}

class FormProfil :

class FormProfil {
  String username;
  int distance;
  int area;
  String coordinates;

  FormProfil ({
    this.username,
    this.distance,
    this.area,
    this.coordinates,
  });

  Map<String, dynamic> toJson() => {
    'username': username.toString(),
    'distance': distance.toString(),
    'area': area.toString(),
    'coordinates': coordinates.toString()
  };

  @override
  String toString() {
    return '{ '
        '${this.username}, '
        '${this.distance}, '
        '${this.area}, '
        '${this.coordinates}, '
    '}';
  }
}

EDIT : I need to create this parent class which contains all the data of my child classes. My child class remains unchanged?

abstract class FormData {
  String username;
  String age;
  String gender;
  int distance;
  int area;
  String coordinates;

  FormData ({
    this.username,
    this.age,
    this.gender,
    this.distance,
    this.area,
    this.coordinates,
  });
}

Upvotes: 0

Views: 38

Answers (1)

Pieter van Loon
Pieter van Loon

Reputation: 5648

Make both classes extend a new abstract class (for instance FormUser) that has all the data you need in the function

And then make the function take a parameter of the new class instead of the FormHome

Upvotes: 1

Related Questions