Flutter: change the width of an AlertDialog

2019-06-23 02:19发布

问题:

I wonder how to change the default width of an AlertDialog, I only succeeded to change the border radius :

Here is my code :

showDialog(
       context: context,
       builder: (_) =>
            new AlertDialog(
               shape: RoundedRectangleBorder(
                   borderRadius: BorderRadius.all(Radius.circular(10.0))
               ),
               content: ProductPreviewScreen(),
            )
    );

Result expected :

Any idea?

回答1:

You could try to wrap your AlertDialog widget with ConstrainedBox widget as suggested in here and set your desired value for maxWidth parameter.

UPDATED

I just looked at the code of the parent of the AlertDialog widget which is the Dialog widget and found out that it wrapped its child with a ConstrainedBox widget with a minWidth of 280 pixels. This is the reason why we can't change the width of the AlertDialog widget.

Fortunately, there are two things that we can do. First option would be to alter the default minWidth of the Dialog Widget inside the dialog.dart file. Note that changing this would affect all of your flutter projects that uses the Dialog widget.

//inside dialog.dart

class Dialog extends StatelessWidget {

...

@override
Widget build(BuildContext context) {
  final DialogTheme dialogTheme = DialogTheme.of(context);
  return AnimatedPadding(
    padding: MediaQuery.of(context).viewInsets + const EdgeInsets.symmetric(horizontal: 40.0, vertical: 24.0),
    duration: insetAnimationDuration,
    curve: insetAnimationCurve,
    child: MediaQuery.removeViewInsets(
      removeLeft: true,
      removeTop: true,
      removeRight: true,
      removeBottom: true,
      context: context,
      child: Center(
        child: ConstrainedBox(
          constraints: const BoxConstraints(minWidth: 280.0), // You can set your desired value for minWidth here
          child: Material(
            elevation: 24.0,

            ...

You can then use the AlertDialog like this:

showDialog(
  context: context,
  builder: (_) => AlertDialog(
    shape: RoundedRectangleBorder(
      borderRadius: BorderRadius.all(Radius.circular(10.0))
      ),
    contentPadding: EdgeInsets.all(0.0),
    content: ProductPreviewScreen(),
    )
  )
);

The other way would be to create our own customize dialog.

showDialog(
  context: context,
  builder: (_) => Center( // Aligns the container to center
    child: Container( // A simplified version of dialog. 
      width: 100.0,
      height: 56.0,
      color: Colors.pink,
      )
    )
 );


回答2:

Get Screen Size:

final screenSize = MediaQuery.of(context).size;

Then Wrap with Container. Use Container width property like this:

width: screenSize.width / 2,

Change 2 with another value for adjust your screen.



标签: dart flutter