Flutter 颤振-Json序列化不起作用

Flutter 颤振-Json序列化不起作用,flutter,dart,Flutter,Dart,我在将数据从服务传递到模型时遇到了一个问题。模型应该从服务获取json,服务从API获取数据,json在模型中转换数据。但在数据传递到模型中之后,映射到JSON的过程就没有了。 我试过很多方法,但结果还是一样 目标\u视图\u服务.dart 从目标和模型得出的结果 您可以复制粘贴运行下面的完整代码 步骤1:\u getGoals()需要返回json.decode(response.body)用于Map 工作演示 完整代码 import 'package:flutter/material.dar

我在将数据从服务传递到模型时遇到了一个问题。模型应该从服务获取json,服务从API获取数据,json在模型中转换数据。但在数据传递到模型中之后,映射到JSON的过程就没有了。 我试过很多方法,但结果还是一样

目标\u视图\u服务.dart 从目标和模型得出的结果
您可以复制粘贴运行下面的完整代码
步骤1:
\u getGoals()
需要返回
json.decode(response.body)用于
Map

工作演示

完整代码

import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.savingsGoalsDic,
  });

  List<GoalsModel> savingsGoalsDic;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        savingsGoalsDic: List<GoalsModel>.from(
            json["savingsGoalsDic__"].map((x) => GoalsModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "savingsGoalsDic__":
            List<dynamic>.from(savingsGoalsDic.map((x) => x.toJson())),
      };
}

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

  int totalAmount;
  int durations;
  String title;

  factory GoalsModel.fromJson(Map<String, dynamic> json) => GoalsModel(
        totalAmount: json["amount"],
        durations: json["duration"],
        title: json["goal_name"],
      );

  Map<String, dynamic> toJson() => {
        "amount": totalAmount,
        "duration": durations,
        "goal_name": title,
      };
}

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

  Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    {"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"}
]
}
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);

    /*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();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GoalViewServices goalViewServices = GoalViewServices();

  Future<List<GoalsModel>> _future;

  @override
  void initState() {
    _future = goalViewServices.renewDataForView();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<GoalsModel>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].title),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].totalAmount
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}
导入“包装:颤振/材料.省道”;
导入“dart:convert”;
将“package:http/http.dart”导入为http;
Payload payloadFromJson(String str)=>Payload.fromJson(json.decode(str));
字符串payloadToJson(有效负载数据)=>json.encode(data.toJson());
类有效载荷{
有效载荷({
这是savingsGoalsDic,
});
列表保存OALSDIC;
工厂负载.fromJson(映射json)=>负载(
savingsGoalsDic:List.from(
json[“savingsGoalsDic_uuu“].map((x)=>GoalsModel.fromJson(x)),
);
映射到JSON()=>{
“储蓄储蓄”:
List.from(savingsGoalsDic.map((x)=>x.toJson()),
};
}
类目标模型{
目标模型({
这个总数,,
这个,持续时间,
这个名字,
});
整数总额;
持续时间;
字符串标题;
工厂GoalsModel.fromJson(映射json)=>GoalsModel(
totalAmount:json[“金额”],
持续时间:json[“持续时间”],
标题:json[“目标名称”],
);
映射到JSON()=>{
“金额”:总金额,
“持续时间”:持续时间,
“目标名称”:标题,
};
}
类目标视图服务{
//列出目标;
var目标=列表();
Future\u getGoals()异步{
字符串jsonString='''
{“savingsGoalsDic_uuuuu”:[{“金额”:123,“期限”:3,“目标名称”:“汽车”},{“金额”:123,“期限”:2,“目标名称”:“住房”},{“金额”:0,“期限”:5,“目标名称”:“退休”},{“金额”:0,“期限”:2,“购物”},{“金额”:0,“期限”:2,“目标名称”:“旅行”},{“金额”:12,“期限”:3,“目标名称”:“婚礼”}
]
}
''';
http.Response=http.Response(jsonString,200);
返回json.decode(response.body);
/*响应请求;
试一试{
request=wait Requests.get(
url+'/savings\u goal\u display',
标题:{'content-type':'application/json'},
//TODO:当具有true ssl证书时,请将verify更改为true。
//验证:false,
timeoutSeconds:20,
);
}捕获(e){
返回{“result”:“连接错误:$e”};
}
如果(!request.hasError){
试一试{
返回request.json()作为映射;
}捕获(e){
返回{“result”:“$e”};
}
}否则{
返回{“结果”:“未知请求错误”};
}*/
}
Future renewDataForView()异步{
var dic=等待_getGoals();
有效载荷;
如果(dic!=null){
有效载荷=有效载荷.fromJson(dic);
}
//印刷(目标);
返回有效载荷.savingsGoalsDic;
}
}
void main(){
runApp(MyApp());
}
类MyApp扩展了无状态小部件{
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
视觉密度:视觉密度。自适应平台密度,
),
主页:MyHomePage(标题:“颤振演示主页”),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
GoalViewServices GoalViewServices=GoalViewServices();
未来,未来;;
@凌驾
void initState(){
_future=goalViewServices.renewDataForView();
super.initState();
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:未来建设者(
未来:未来,
生成器:(上下文,异步快照){
交换机(快照.连接状态){
案例连接状态。无:
返回文本(“无”);
案例连接状态。正在等待:
返回中心(子项:CircularProgressIndicator());
案例连接状态.active:
返回文本(“”);
案例连接状态。完成:
if(snapshot.hasError){
返回文本(
“${snapshot.error}”,
样式:TextStyle(颜色:Colors.red),
);
}否则{
返回ListView.builder(
itemCount:snapshot.data.length,
itemBuilder:(上下文,索引){
回程卡(
标高:6.0,
孩子:填充(
填充:仅限常量边设置(
排名:6.0,
底部:6.0,
左:8.0,
右:8.0),
孩子:排(
crossAxisAlignment:crossAxisAlignment.start,
儿童:[
文本(快照.数据[索引].标题),
垫片(),
正文(
snapshot.data[index].totalAmount
.toString(),
),
],
),
));
});
}
}
}));
}
}
唯一可能的呼叫
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,

  };

}
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;
  }

}

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}]
[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']
Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    ...
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);
Future<List<GoalsModel>> renewDataForView() async {
    var dic = await _getGoals();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  } 
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;

Payload payloadFromJson(String str) => Payload.fromJson(json.decode(str));

String payloadToJson(Payload data) => json.encode(data.toJson());

class Payload {
  Payload({
    this.savingsGoalsDic,
  });

  List<GoalsModel> savingsGoalsDic;

  factory Payload.fromJson(Map<String, dynamic> json) => Payload(
        savingsGoalsDic: List<GoalsModel>.from(
            json["savingsGoalsDic__"].map((x) => GoalsModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => {
        "savingsGoalsDic__":
            List<dynamic>.from(savingsGoalsDic.map((x) => x.toJson())),
      };
}

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

  int totalAmount;
  int durations;
  String title;

  factory GoalsModel.fromJson(Map<String, dynamic> json) => GoalsModel(
        totalAmount: json["amount"],
        durations: json["duration"],
        title: json["goal_name"],
      );

  Map<String, dynamic> toJson() => {
        "amount": totalAmount,
        "duration": durations,
        "goal_name": title,
      };
}

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

  Future<Map<String, dynamic>> _getGoals() async {
    String jsonString = '''
    {"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"}
]
}
    ''';
    http.Response response = http.Response(jsonString, 200);

    return json.decode(response.body);

    /*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();
    Payload payload;
    if (dic != null) {
      payload = Payload.fromJson(dic);
    }
    // print(goals);
    return payload.savingsGoalsDic;
  }
}

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  GoalViewServices goalViewServices = GoalViewServices();

  Future<List<GoalsModel>> _future;

  @override
  void initState() {
    _future = goalViewServices.renewDataForView();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: Text(widget.title),
        ),
        body: FutureBuilder(
            future: _future,
            builder: (context, AsyncSnapshot<List<GoalsModel>> snapshot) {
              switch (snapshot.connectionState) {
                case ConnectionState.none:
                  return Text('none');
                case ConnectionState.waiting:
                  return Center(child: CircularProgressIndicator());
                case ConnectionState.active:
                  return Text('');
                case ConnectionState.done:
                  if (snapshot.hasError) {
                    return Text(
                      '${snapshot.error}',
                      style: TextStyle(color: Colors.red),
                    );
                  } else {
                    return ListView.builder(
                        itemCount: snapshot.data.length,
                        itemBuilder: (context, index) {
                          return Card(
                              elevation: 6.0,
                              child: Padding(
                                padding: const EdgeInsets.only(
                                    top: 6.0,
                                    bottom: 6.0,
                                    left: 8.0,
                                    right: 8.0),
                                child: Row(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: <Widget>[
                                    Text(snapshot.data[index].title),
                                    Spacer(),
                                    Text(
                                      snapshot.data[index].totalAmount
                                          .toString(),
                                    ),
                                  ],
                                ),
                              ));
                        });
                  }
              }
            }));
  }
}