如何将参数传递给有状态的小部件?

时间:2019-10-04 10:50:30

标签: flutter dart

我有以下状态控件

class MyDiaryScreen2 extends StatefulWidget {
  final AnimationController animationController;
  MyDiaryScreen2({Key key, this.animationController}) : super(key: key);
  @override
  _MyDiaryScreen2State createState() => _MyDiaryScreen2State();
  int index;
}

class _MyDiaryScreen2State extends State<MyDiaryScreen2>
    with TickerProviderStateMixin {
  Animation<double> topBarAnimation;

  List<Widget> listViews = List<Widget>();
  var scrollController = ScrollController();
  double topBarOpacity = 1.0;
}

我从另一个小部件将此小部件称为

onTap: () {MyDiaryScreen2();},

但是我想像这样将类型为int的MealsView.index参数传递给MyDiaryScreen2

onTap: () {MyDiaryScreen2(MealsView.index);},

我该如何实现?

1 个答案:

答案 0 :(得分:3)

您只需在初始化MyDiaryScreen2时将其作为普通参数传递即可:

onTap: () => MyDiaryScreen2(
  animationController: <controller>,
  index: MealsView.index,
)

当然,不要忘记调整MyDiaryScreen2使其在构造函​​数中接受index

class MyDiaryScreen2 extends StatefulWidget {
  final AnimationController animationController;
  final int index;

  MyDiaryScreen2({Key key, this.animationController, this.index}) : super(key: key);

  @override
  _MyDiaryScreen2State createState() => _MyDiaryScreen2State();
}