【发布时间】:2018-12-13 15:34:45
【问题描述】:
我是 Flutter 开发的初学者,但遇到了一些问题。我会尽力向我解释。
我有一个滑块(自定义小部件有状态)。我想将此小部件集成到我的主视图中,但我必须更改滑块的值(此值也可以通过点击手势检测器更改)。
我在网上研究后尝试了几件事。
例如,使用 VerticalSliderState 的 getter 并访问 VerticalSliderState 方法来更改值。
这仅在我收到 the state is null 错误后才起作用,我想我错过了 setState() 的颤振概念。
有什么解释吗?谢谢:P
这是我的代码:
有状态的自定义小部件:
import 'package:flutter/material.dart';
class VerticalSlider extends StatefulWidget {
....
final double value;
.....
final void Function(double) onValueChanged;
VerticalSlider({
Key key,
@required this.height,
@required this.width,
this.onValueChanged,
this.value,
....
}) : super(key: key);
VerticalSliderState state;
@override
VerticalSliderState createState(){
state = new VerticalSliderState();
return state ;
}
}
class VerticalSliderState extends State<Vertical Slider>{
.....
double _value;
double _currentHeight;
Widget _movingDecoratedBox;
Widget _fixedDecoratedBox;
void setValue(double value){
_setValue(value, false, widget.height);
}
initState() {
super.initState();
_value = widget.value ?? 5.0;
_currentHeight = _convertValueToHeight();
_movingDecoratedBox = widget.movingBox ?? DecoratedBox(
decoration: BoxDecoration(color: Colors.red)
);
_fixedDecoratedBox = widget.fixedBox ?? DecoratedBox(
decoration: BoxDecoration(color: Colors.grey),
);
}
..........
void _onTapUp(TapUpDetails tapDetails) {
RenderBox renderBox = context.findRenderObject();
var newHeight = widget.height - renderBox.globalToLocal(tapDetails.globalPosition).dy;
var newValue = _convertHeightToValue(newHeight);
setState(() {
_currentHeight = (widget.height/10.5) * (newValue);
_setValue(newValue, true, widget.height);
});
}
void _setValue(double newValue, bool userRequest, double height) {
_value = newValue;
if(userRequest){
widget.onValueChanged(_value);
}
else{
setState(() {
_currentHeight = (height/10.5) * (newValue);
});
}
}
Widget _buildMovingBox() {
return Align(
alignment: Alignment.bottomCenter,
child: SizedBox(
width: widget.width,
height: _currentHeight,
child: _movingDecoratedBox,
),
);
}
..........
@override
Widget build(BuildContext context) {
return GestureDetector(
onTapUp: _onTapUp,
child: Stack(
alignment: AlignmentDirectional.bottomCenter,
children: <Widget>[
_buildFixedBox(),
_buildMovingBox(),
],
),
);
}
我的主要观点:
seekBar1 = new VerticalSlider(
height: mediaQueryData.size.height / 2.7,
width: 40.0,
max: 11.0,
min: 0.0,
value: 5.5,
movingBox: new Container(color: Colors.teal),
fixedBox: new Container(color: Colors.grey[200]),
onValueChanged: onValueChanged1,
);
void onValueChanged1(double newValue) {
seekBar2.state.setValue(10-newValue);
print(newValue);
}
【问题讨论】: