多个类的全局变量

时间:2019-04-26 16:09:47

标签: dart flutter

我正在扑朔迷离地创建一个简单的时间选择器。我有一个主要的TimePicker类,另外两个类分别包含gridView-,用于显示小时和分钟。从其他类别中选择图形后,我需要将它们发送到主TimePicker进行显示。

import 'package:flutter/material.dart';

//my "Global variables"!
String hourPicked = '';
String minPicked = '';

// Main class
class TimePickerDialog extends StatefulWidget {
  @override
  _TimePickerDialogState createState() => _TimePickerDialogState();
}

class _TimePickerDialogState extends State<TimePickerDialog> {
...
@override
  Widget build(BuildContext context) {
...

// Inside here somewhere, display the picked time.
Text('$hourPicked : $minPicked')

//the other classes are children here. 
//not exactly like this tho, this is for demonstration
Column(
  children: [
    GridViewHourPicker(),
    GridViewMinutesPicker(),
  ]
...
}
}

//class for hour gridView
class GridViewHourPicker extends StatefulWidget {
  @override
  _GridViewHourPickerState createState() => _GridViewHourPickerState();
}

class _GridViewHourPickerState extends State<GridViewHourPicker> {
...

// Somewhere in here, set hourPicked variable when a button is clicked
  setState(() {
    hourPicked = '2';
    });

...
}

//class for minute gridView
class GridViewMinutesPicker extends StatefulWidget {
  @override
  __GridViewMinutesPickerState createState() => __GridViewMinutesPickerState();
}

class __GridViewMinutesPickerState extends State<_GridViewMinutesPicker> {
...

// Somewhere in here, set minPicked variable when a button is clicked
  setState(() {
    minPicked = '42';
    });

...
}


这以某种方式起作用。可以正确设置变量,但是更改不会反映在主类中。

是否存在可以完成类似操作的宇宙,该如何完成? 有什么更好的工作选择。 注意:类完全像这样堆叠在单个文件中。

0 个答案:

没有答案