如何使用从 Flutter 中的 json 解析的嵌套映射列表中的函数创建对象

Posted

技术标签:

【中文标题】如何使用从 Flutter 中的 json 解析的嵌套映射列表中的函数创建对象【英文标题】:How do i create an object using a function from a list of nested maps parse from json in Flutter 【发布时间】:2021-01-14 14:56:19 【问题描述】:

我正在寻求帮助扩展之前的问题Question,该问题向我展示了一种访问MovementDataSource 中的 json 数据的方法。在这种情况下,在第一页上,使用列表视图和getMovements() 向用户呈现移动列表。选择一个动作后,第 2 页上的用户会通过列表视图和getVariationsByMovement() 看到一个变化列表。然后在选择变体后,用户会看到第 3 页,它让我可以访问单数 VariationModel 中的所有项目。 (现在只是变体名称)

我有另一个用例,我在应用程序的另一部分,但需要绕过上面第 1 页和第 2 页的用户工作流程直接跳转到第 3 页。那时我可以访问String MovementString VariationName。我正在寻求帮助 - 我可以传入这两个变量并返回一个 VariationName 对象以将链接的构造函数直接传递到第 3 页的函数示例。在下面的 MovementDataSource 中有一个getVariation() 函数我希望能得到帮助。

class MovementDataSource extends ChangeNotifier

  List<Map> getAll() => _movement;

  List<String> getMovements()=> _movement
      .map((map) => MovementModel.fromJson(map))
      .map((item) => item.movement)
      .toList();

  getVariationsByMovement(String movement) => _movement
      .map((map) => MovementModel.fromJson(map))
      .where((item) => item.movement == movement)
      .map((item) => item.variation)
      .expand((i) => i)
      .toList();

  VariationModel getVariation(String movement, String variation)
       **Return VariationModel from List _movement json**
  


  List _movement = [
    
      "movement": "Plank",
      "alias": "plank",
      "variation": [
        "variationName": "High Plank", "variationName": "Forearm Plank",
      ]
    ,
    
      "movement": "Side Plank",
      "alias": "side plank",
      "variation": [
        "variationName": "Side Plank Right", "variationName": "Side Plank Left",
      ],
    ,
  ];


class MovementModel 
  MovementModel(
    this.movement,
    this.alias,
    this.variation,
  );

  String movement;
  String alias;
  List<VariationModel> variation;

  factory MovementModel.fromJson(Map<String, dynamic> json) => MovementModel(
        movement: json["movement"],
        alias: json["alias"],
        variation: List<VariationModel>.from(
            json["variation"].map((x) => VariationModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => 
        "movement": movement,
        "alias": alias,
        "variation": List<dynamic>.from(variation.map((x) => x.toJson())),
      ;


class VariationModel 
  VariationModel(
    this.variationName,
  );

  String variationName;

  factory VariationModel.fromJson(Map<String, dynamic> json) => VariationModel(
        variationName: json["variationName"],
      );

  Map<String, dynamic> toJson() => 
        "variationName": variationName,
      ;

上面第 3 页的示例 - 本用例中的直接目标。

class TargetPage extends StatelessWidget 
  final VariationModel variation;
  SelectDefaultItemPage(this.variation);

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text("test"),
        ),
        body: Text(variation.variationName));
  

包含指向上述第 3 页目标的直接链接的源页面示例。这是调用 getVariation() 函数的地方,将 VariationModel 传递给上面的 SourcePage。

class SourcePage extends StatelessWidget 
  final VariationModel variation;
  SelectDefaultItemPage(this.variation);

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text("test"),
        ),
        body:FlatButton(
              child: Text(
                "Go to TargetPage",
              ),
              onPressed: () async Navigator.push(context, MaterialPageRoute(
                            builder: (_) => SourcePage(getVariation(movement: movement, variation: 
                            variation)));
              ,
         )
  


感谢您的帮助。

【问题讨论】:

【参考方案1】:

您可以在下面复制粘贴运行完整代码 您可以将movementDataSourcemovementvariation 传递给SourcePage 并在SourcePage 通话中

TargetPage(variation: movementDataSource.getVariation(
                            movement: movement,
                            variation: variation.variationName))

代码sn-p

VariationModel getVariation(String movement, String variation) => _movement
      .map((map) => MovementModel.fromJson(map))
      .where((item) => item.movement == movement)
      .map((item) => item.variation)
      .expand((i) => i)
      .where((e) => e.variationName == variation)
      .first;
...
onTap: () async 
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (_) => SourcePage(
                              movementDataSource: _movementDataSource,
                              movement: movement,
                              variation: vList[index])));
                ,
                
...             
class SourcePage extends StatelessWidget 
  final MovementDataSource movementDataSource;
  final String movement;
  final VariationModel variation;
  SourcePage(this.movementDataSource, this.movement, this.variation);

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        ...
          onPressed: () async 
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (_) => TargetPage(
                        variation: movementDataSource.getVariation(
                            movement: movement,
                            variation: variation.variationName))));
          ,
        ));     

...
class TargetPage extends StatelessWidget 
  final VariationModel variation;
  TargetPage(this.variation);
        

工作演示

完整代码

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

List<MovementModel> movementModelFromJson(String str) =>
    List<MovementModel>.from(
        json.decode(str).map((x) => MovementModel.fromJson(x)));
String movementModelToJson(List<MovementModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class MovementDataSource extends ChangeNotifier 
  List<Map> getAll() => _movement;

  List<String> getMovements() => _movement
      .map((map) => MovementModel.fromJson(map))
      .map((item) => item.movement)
      .toList();

// I'd  like this to return a list of movement.variation.variationName

  getVariationsByMovement(String movement) => _movement
      .map((map) => MovementModel.fromJson(map))
      .where((item) => item.movement == movement)
      .map((item) => item.variation)
      .expand((i) => i)
      .toList();

  VariationModel getVariation(String movement, String variation) => _movement
      .map((map) => MovementModel.fromJson(map))
      .where((item) => item.movement == movement)
      .map((item) => item.variation)
      .expand((i) => i)
      .where((e) => e.variationName == variation)
      .first;

  List _movement = [
    
      "movement": "Plank",
      "alias": "plank",
      "variation": [
        "variationName": "High Plank",
        "variationName": "Forearm Plank",
      ]
    ,
    
      "movement": "Side Plank",
      "alias": "side plank",
      "variation": [
        "variationName": "Side Plank Right",
        "variationName": "Side Plank Left",
      ],
    ,
  ];


class MovementModel 
  MovementModel(
    this.movement,
    this.alias,
    this.variation,
  );

  String movement;
  String alias;
  List<VariationModel> variation;

  factory MovementModel.fromJson(Map<String, dynamic> json) => MovementModel(
        movement: json["movement"],
        alias: json["alias"],
        variation: List<VariationModel>.from(
            json["variation"].map((x) => VariationModel.fromJson(x))),
      );

  Map<String, dynamic> toJson() => 
        "movement": movement,
        "alias": alias,
        "variation": List<dynamic>.from(variation.map((x) => x.toJson())),
      ;


class VariationModel 
  VariationModel(
    this.variationName,
  );

  String variationName;

  factory VariationModel.fromJson(Map<String, dynamic> json) => VariationModel(
        variationName: json["variationName"],
      );

  Map<String, dynamic> toJson() => 
        "variationName": variationName,
      ;


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> 
  int _counter = 0;
  String movement = "Plank";
  MovementDataSource _movementDataSource = MovementDataSource();
  void _incrementCounter() 
    List<VariationModel> vList =
        _movementDataSource.getVariationsByMovement("Plank");

    for (int i = 0; i < vList.length; i++) 
      print(vList[i].variationName);
    

    setState(() 
      _counter++;
    );
  

  @override
  Widget build(BuildContext context) 
    List<VariationModel> vList =
        _movementDataSource.getVariationsByMovement(movement);

    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          itemCount: vList.length,
          itemBuilder: (buildContext, index) 
            return Card(
              child: ListTile(
                title: Text(
                  vList[index].variationName.toString(),
                  style: TextStyle(fontSize: 20),
                ),
                trailing: Icon(Icons.keyboard_arrow_right),
                onTap: () async 
                  Navigator.push(
                      context,
                      MaterialPageRoute(
                          builder: (_) => SourcePage(
                              movementDataSource: _movementDataSource,
                              movement: movement,
                              variation: vList[index])));
                ,
              ),
            );
          ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  


class SourcePage extends StatelessWidget 
  final MovementDataSource movementDataSource;
  final String movement;
  final VariationModel variation;
  SourcePage(this.movementDataSource, this.movement, this.variation);

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text("Source page"),
        ),
        body: FlatButton(
          child: Text(
            "Go to TargetPage",
          ),
          onPressed: () async 
            Navigator.push(
                context,
                MaterialPageRoute(
                    builder: (_) => TargetPage(
                        variation: movementDataSource.getVariation(
                            movement: movement,
                            variation: variation.variationName))));
          ,
        ));
  


class TargetPage extends StatelessWidget 
  final VariationModel variation;
  TargetPage(this.variation);

  @override
  Widget build(BuildContext context) 
    return Scaffold(
        appBar: AppBar(
          title: Text("Target page"),
        ),
        body: Text(variation.variationName));
  

【讨论】:

这正是我想要的。我希望在您提供的答案之间,我可以开始对如何更好地使用列表、地图和数据进行三角测量。您是否知道使用 function() =&gt; data.doSomething.doSomething 结构关注这一领域的任何文档或教程? @nejas,可以参考codeburst.io/…和bezkoder.com/dart-list

以上是关于如何使用从 Flutter 中的 json 解析的嵌套映射列表中的函数创建对象的主要内容,如果未能解决你的问题,请参考以下文章

如何在 Flutter 中解析这个 JSON 数组?

如何将flutter中的日期解析为与Java ZonedDateTime兼容的json字符串

Flutter 中的 JSON 数据解析

如何将复杂(嵌套)对象解析为 JSON 并在 Flutter 中使用 HTTP 将其发送到服务器?

Flutter 如何从 JSON 中列出具有多个子项的数组

flutter : 嵌套的 json 解析列表