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

How do i create an object using a function from a list of nested maps parse from json in Flutter

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

我有另一个用例,我在应用程序的另一部分,但需要绕过上面第 1 页和第 2 页的用户工作流直接跳转到第 3 页。那时我可以访问 String MovementString VariationName。我正在寻求帮助 - 一个函数示例,我可以传入这两个变量并返回一个 VariationName 对象以将 link 的构造函数直接传递到第 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));
  }
}

包含直接 link 到上面第 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)));
              },
         )
  }
}

感谢您的帮助。

您可以复制粘贴运行下面的完整代码
您可以将 movementDataSourcemovementvariation 传递给 SourcePage
并在 SourcePage 调用

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

代码片段

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