如何在StatelessWidget中使用showModalBottomSheet?

时间:2019-04-11 08:09:43

标签: dart flutter

我尝试这样编码

showModalBottomSheet(
   context: context, // I got error here (Undefined name 'context'.dart(undefined_identifier))
   builder: (context){

   return Container(

   );
);

我在context: context上遇到错误,错误消息是

  

未定义名称'context'.dart(undefined_identifier)

3 个答案:

答案 0 :(得分:3)

这就是您在showModalBottomSheet中调用StatelessWidget

的方式
class TestStatelessWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {

    return RaisedButton(
      child: Text('Press me'),
      onPressed: ()=>showPress(context),
    );
  }

  void showPress(BuildContext context){
    showModalBottomSheet(context:context, builder: (context){
      return Text('hello');
    });
  }



}

答案 1 :(得分:1)

您收到此错误,是因为您无法在 deltaX = deltaY = 2;//px var element = document.getElementById('divID'); element.addEventListener("mousedown", function(e){ if (typeof InitPageX == 'undefined' && typeof InitPageY == 'undefined') { InitPageX = e.pageX; InitPageY = e.pageY; } }, false); element.addEventListener("mousemove", function(e){ if (typeof InitPageX !== 'undefined' && typeof InitPageY !== 'undefined') { diffX = e.pageX - InitPageX; diffY = e.pageY - InitPageY; if ( (diffX > deltaX) || (diffX < -deltaX) || (diffY > deltaY) || (diffY < -deltaY) ) { console.log("dragging");//dragging event or function goes here. } else { console.log("click");//click event or moving back in delta goes here. } } }, false); element.addEventListener("mouseup", function(){ delete InitPageX; delete InitPageY; }, false); element.addEventListener("click", function(){ console.log("click"); }, false); 类中的任何地方访问context。您需要做的就是从StatelessWidget传递context(如果您在build()方法之外使用此方法,否则在build()方法中使用它)。


解决方案1。(在build()内部使用)

build()

解决方案2。(在@override Widget build(BuildContext context) { return RaisedButton( child: Text("Show sheet"), onPressed: () { showModalBottomSheet(context: context, builder: (context) => YourWidget()); }, ); } 外部使用)

build()

答案 2 :(得分:0)

您没有正确关闭showModalBottomSheet的{​​{1}}。 缺少builder

这将是正确的用法:

}