FilledStacks / flutter-tutorials

The repo contains the source code for all the tutorials on the FilledStacks Youtube channel.
MIT License
4.75k stars 1.76k forks source link

data from services to model not working #72

Closed AlohaTiger closed 4 years ago

AlohaTiger commented 4 years ago

Hi,

I followed provider and get_it tutorial and used in my projects. I have encountered an issue passing data from services to models. May you help me to check my problem. I have tried it in many ways

goals_view_service.dart

import 'dart:convert';
import 'package:requests/requests.dart';

// goal_data={
  //        [
//         'goal_name': savings_goal[1],
//         'amount': savings_goal[2],
//         'duration': savings_goal[3],
//       ]
//          }

class GoalViewServices{

  // List<GoalsModel> _goals;
  var goals = List<GoalsModel>();

   Future<Map<String, dynamic>> _getGoals() async {
      Response request;
      try {
        request = await Requests.get(
          url + '/savings_goal_display',
          headers: {'content-type': 'application/json'},
          // TODO: when having true ssl certificate, change verify to true.
          // verify: false,
          timeoutSeconds: 20,
        );
      } catch (e) {
        return {"result": "Connection Error: $e"};
      }
      if (!request.hasError) {
        try {
          return request.json() as Map<String, dynamic>;
        } catch (e) {
          return {"result": "$e"};
        }
      } else {
        return {"result": "Unknown Request Error"};
      }
  }

  Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    // var goals = List<GoalsModel>();
    if (dic != null) {
      // print(dic);
      // final savingsGoalsDic = dic['saving_goals'];
      final savingsGoalsDicArray = List<Map<String, dynamic>>.from(dic['savings_goals'] ?? {}) ?? [];
      // final savingsGoalsDicArray = (dic['savings_goals'] ?? {}) ?? [];
      print('savingsGoalsDic__: $savingsGoalsDicArray');
      for (final aData in savingsGoalsDicArray) {
          // print(aData);
          // Map json = jsonDecode(aData);
          // var title = aData["goal_name"];
          // var totalAmount = aData["amount"];
          // var durations = aData["duration"];
          goals.add(GoalsModel.fromJson(aData));
        }
    }
    // print(goals);
    return goals;
  }

}

goals_model.dart

class GoalsModel {
  String title;
  String imagePath;
  int totalAmount;
  int durations;

  GoalsModel({this.title,this.totalAmount,this.durations});

  // final Map<String, String> goalsImage = {
  //   "Housing": "assets/images/housing.jpg",
  //   "Car": "assets/images/car.jpg",
  //   "Retirement": "assets/images/retirement.jpg",
  //   "Shopping": "assets/images/shopping.jpg",
  //   "Travel": "assets/images/travel.jpg",
  //   "Wedding": "assets/images/wedding.jpg",
  //   "Study": "assets/images/study.jpg"
  // };

  GoalsModel.fromJson(Map<String, dynamic> json) {

    // print(json);
    title = json["goal_name"] as String;
    // print(this.title);
    totalAmount = json["amount"] as int;
    // print(this.totalAmount);
    durations = json["duration"] as int;
    // print(this.durations);
    imagePath = "assets/images/study.jpg";
    // var data = _toJson(this.title,this.imagePath,this.totalAmount,this.durations);    

    // if (this.title == goals.keys){
    //     this.imagePath = goals.values;
    // }
  }

  // GoalsModel.fromJson(Map<String, dynamic> json)
  //     : title = json["goal_name"],
  //       totalAmount = json["amount"],
  //       durations = json["duration"],
  //        imagePath = "assets/images/study.jpg";

  Map<String, dynamic> toJson () =>{
    'title' : title,
    'imagePath' :imagePath,
    'totalAmount' : totalAmount,
    'durations': durations,

  };

}

Goals_viewmodels.dart

class GoalsViewModel extends BaseModel {
    GoalViewServices _goalViewServices=locator<GoalViewServices>();

    List<GoalsModel> goalList;

    Future<List<GoalsModel>> getGoals() async {
    setState(ViewState.Busy);
    goalList = await _goalViewServices.renewDataForView();
    print(goalList);
    setState(ViewState.Idle);
    return goalList;
  }

}

Goals Dictionary

savingsGoalsDic__: [{amount: 123, duration: 3, goal_name: Car}, {amount: 123, duration: 2, goal_name: Housing}, {amount: 0, duration: 5, goal_name: Retirement}, {amount: 0, duration: 2, goal_name: Shopping}, {amount: 0, duration: 2, goal_name: Travel}, {amount: 12, duration: 3, goal_name: Wedding}]

Result from Goals_model

[Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel', Instance of 'GoalsModel']