MaterialButton 内的 Flutter 容器宽度

问题描述

我尝试了几个小时将我的容器宽度设置为其父级,即 MaterialButton。我希望容器填满 MaterialButton 的整个宽度。

我尝试将容器宽度设置为“double.infitiy”或“MediaQuery.of(context).size.width”。还玩过“Expanded”等。都没有奏效。不知道我做错了什么,谢谢。

@override
  Widget build(BuildContext context) {
    return Material(
      **child: MaterialButton(
        minWidth: MediaQuery.of(context).size.width,onpressed: onpressed,child: Container(
          width: double.infinity,**
          margin: EdgeInsets.all(8.0),padding: EdgeInsets.all(8.0),decoration: Boxdecoration(
              color: Colors.greenAccent,borderRadius: BorderRadius.circular(10.0)),child: Column(
            mainAxisAlignment: MainAxisAlignment.center,children: [
              Text(text),SizedBox(
                height: 8.0,),SvgPicture.asset(
                'images/medaillen.svg',width: 80,SizedBox(
                height: 15.0,Text(
                textTopThree,maxLines: 3,],);

解决方法

我建议你用 InkWell 替换 Material Button,你可以包装任何小部件并获得 onTap。

这应该有效:

InkWell(
            onTap: () {},child: Container(
              width: double.infinity,padding: EdgeInsets.all(8.0),decoration: BoxDecoration(
                color: Colors.greenAccent,borderRadius: BorderRadius.circular(10.0),),child: Column(
                children: [
                  Text('Button Text'),SizedBox(
                    height: 8.0,Image.asset(
                      'images/medaillen.svg',width: 80,SizedBox(
                    height: 15.0,Text(
                    'textTopThree',maxLines: 3,],

如果由于某种原因需要使用 MaterialButton,那么您应该删除 Container 并使用 Material Button 的属性,如下所示:

MaterialButton(
            onPressed: () {},color: Colors.greenAccent,minWidth: double.infinity,shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(18.0),child: Column(
              children: [
                SizedBox(
                  height: 8.0,Text('Button Text'),SizedBox(
                  height: 8.0,Image.asset(
                  'images/medaillen.svg',SizedBox(
                  height: 15.0,Text(
                  'textTopThree',