访问列表从一种飞镖扑向另一种飞镖

时间:2020-09-10 07:38:14

标签: list flutter

如何从一个飞镖访问下面的变量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变量?

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

像mak所说的那样导入此文件。

使用诸如Riverpod和提供者之类的州管理解决方案将更加清洁。