所以我有一个滑块,应该可以更改GLOBAL变量的值。这是TimeData类,在提供程序包中引用。
import 'package:flutter/foundation.dart';
class TimeData extends ChangeNotifier {
int seconds = 10;
void setTime(int time) {
time = seconds;
notifyListeners();
}
int getTime() {
return seconds;
}
}
然后,这是应该能够更改秒数的滑块:
Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.baseline,
textBaseline: TextBaseline.alphabetic,
children: <Widget>[
Text(
Provider.of<TimeData>(context, listen: false)
.getTime()
.toString(),
style: TextStyle(
color: Colors.white,
fontSize: 60,
),
),
Text(
's',
style: TextStyle(
color: Colors.white,
fontSize: 30,
),
),
],
),
SizedBox(
height: 10,
),
SliderTheme(
data: SliderTheme.of(context).copyWith(
activeTrackColor: Colors.white,
inactiveTrackColor: Colors.black87,
thumbColor: Colors.white,
overlayColor: Colors.white70,
thumbShape: RoundSliderThumbShape(
enabledThumbRadius: 15.0,
),
overlayShape: RoundSliderOverlayShape(
overlayRadius: 30.0,
),
),
child: Container(
width: 350,
child: Slider(
value: Provider.of<TimeData>(context, listen: false)
.getTime()
.toDouble(),
min: 10,
max: 180,
onChanged: (double newValue) {
setState(() {
//duration = newValue.round();
//ToDo: Fix the current duration bug and make duration a global variable
Provider.of<TimeData>(context, listen: false)
.setTime(newValue.toInt());
print(Provider.of<TimeData>(context, listen: false)
.getTime());
});
},
),
),
),
当然,如果我使listen == true(默认),则会出现错误消息,提示我当前不在我的Widget树之外,因此应将listen == false。滑块完全没有改变,我也没有更改默认值10。(如果我没有默认值,则滑块无法首先建立)。
[基本上,我需要解决无法更改全局变量秒数的问题。希望您能理解我对问题的解释:)
您可以参考此issue。此示例说明如何声明单例变量。