繁体   English   中英

访问列表从一个飞镖跳到另一个飞镖

[英]Access List flutter from one dart to another

如何从一个飞镖访问下面的变量availableList

class Excerciselist extends StatefulWidget {
  final String value;

  Excerciselist( this.value );
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _MyExc();  }
}

ImageSequenceAnimatorState imageSequenceAnimator;

void onReadyToPlay(ImageSequenceAnimatorState _imageSequenceAnimator) {
  imageSequenceAnimator = _imageSequenceAnimator;
}
final List<Exercise> availableList = [
  Exercise(
      name: "Pushups",
      imageUrl: "imagesfirst",
      duration: "20"),
  Exercise(
      name: "Chinups",
      imageUrl: "second",
      duration: "20"),
  Exercise(

如何访问另一个 dart 文件中的 availableList 变量?

class Excerciselist {

  String name;
  String imageUrl;
  String duration;

  Excerciselist({
    this.name,
    this.imageUrl,
    this.duration,
  });

  static List<Excerciselist> availableList = [
    Excerciselist(name: "Pushups", imageUrl: "imagesfirst", duration: "20"),
    Excerciselist(name: "Chinups", imageUrl: "second", duration: "20"),
  ];
}

然后将其导入您的文件,您可以列出项目,例如:


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

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

class MyApp extends StatelessWidget {
  List _list = Excerciselist.availableList;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        home: Scaffold(
      body: ListView(
          children: [
        ..._list.map((data) {
          return Column(
            children: [Text('${data.name}'), Text('${data.imageUrl}')],
          );
        })
      ].toList()),
    ));
  }
}


================

您还可以创建用于操作数据的实例和方法,例如查找总持续时间。

class Excerciselist {

// adding these two lines
  static Excerciselist instance = Excerciselist._();
  Excerciselist._();
// ==

  String name;
  String imageUrl;
  String duration;

  Excerciselist({
    this.name,
    this.imageUrl,
    this.duration,
  });


  static List<Excerciselist> availableList = [
    Excerciselist(name: "Pushups", imageUrl: "imagesfirst", duration: "20"),
    Excerciselist(name: "Chinups", imageUrl: "second", duration: "20"),
  ];

// Create the method

  durationOf() {
    int totalDur = 0;
    availableList.forEach((element) {
      totalDur = totalDur + int.parse(element.duration);
    });
    return totalDur;
  }


//
}

您可以在主文件中调用它:

Excerciselist <name> = Excerciselist.instance;

然后在您的小部件中使用它: <name>.durationOf()

像麦说的那样导入这个文件。

使用诸如 riverpod 和 provider 之类的状态管理解决方案会更干净。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM