How do I return the values of a nested structure with a list of maps in Flutter

我们两清 提交于 2021-01-02 03:52:16

问题


Still trying to learn maps and lists.

My goal is to return a list from a nested list of maps. The function getMovements() works as expected. It renders a list of movements. Then I try to create another function getVariationsByMovement() which passes in the movement string name to attempt to return a list of variationNames. In my UI, I present a list of movements. The user selects a movements and the next page renders with a list of variations.

I am stuck in the function below getVariationsByMovement.

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.**I AM STUCK HERE**)
      .expand((i) => i)
      .toList();


  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"},
      ],
    },
  ];
}

My model

class MovementModel {
  String movement;
  String alias;
  List<VariationModel> variation;

  MovementModel({this.movement, this.alias, this.variation});

  // from firestore
  MovementModel.fromJson(Map<String, dynamic> json) {
    var list = json['variation'] as List;
    List<VariationModel> variationList = list.map((i) => VariationModel.fromJson(i)).toList();
    movement = json['movement'];
    alias = json['alias'];
    variation = variationList;
  }

  // to firestore
  Map<String, dynamic> toJson() {
  final Map<String, dynamic> data = new Map<String, dynamic>();
  data['movement'] = this.movement;
  data['alias'] = this.alias;
  //data['variation'] = VariationModel;
  return data;
  }
}

class VariationModel {
  String variationName;
  String description;

  VariationModel({this.variationName, this.description});

  // from firestore
  VariationModel.fromJson(Map<String, dynamic> json) {
    variationName = json['variationName'];
    description = json['description'];
  }

  // to firestore
  Map<String, dynamic> toJson() {

    return {
      'variationName': variationName,
      'description': description,
    };
  }
}

UPDATE In this case I am trying to return the results to a list builder.

  @override
  Widget build(BuildContext context) {
    final _movementDataLocator = locator<MovementDataSource>();
    return ListView.builder(
        scrollDirection: Axis.vertical,
        shrinkWrap: true,
        itemCount: _movementDataLocator.getVariationsByMovement(movement).length,
        itemBuilder: (buildContext, index) {
          return Card(
            child: ListTile (
              title: Text(
                _movementDataLocator.getVariationsByMovement(movement)[index].toString(),
                style: TextStyle(fontSize: 20),
              ),
              trailing: Icon(Icons.keyboard_arrow_right),
              onTap: () async {
                Navigator.push(context, MaterialPageRoute(
                    builder: (_) => SelectDefaultItemPage(variation: _movementDataLocator.getVariationsByMovement(movement)[index])));
              },
            ),
          );
        }
    );
  }
}


回答1:


You can copy paste run full code below
You can use variation: List<VariationModel>.from(json["variation"].map((x) => VariationModel.fromJson(x))
code snippet

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))),
      );
      
...
List<VariationModel> vList =
        MovementDataSource().getVariationsByMovement("Plank");

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

output

I/flutter (21879): High Plank
I/flutter (21879): Forearm Plank

full code

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

  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;

  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) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

working demo

full code 2

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

  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;

  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("Plank");

    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: (_) =>
                              SelectDefaultItemPage(variation: vList[index])));
                },
              ),
            );
          }),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}

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

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


来源:https://stackoverflow.com/questions/64055854/how-do-i-return-the-values-of-a-nested-structure-with-a-list-of-maps-in-flutter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!