Flutter: ListView in a SimpleDialog

后端 未结 9 1697
深忆病人
深忆病人 2020-12-24 01:04

I want to show a SimpleDialog with ListView.builder in my Flutter app with this code:

showDialog(
  context: context,
  builder: (BuildContext context) {
           


        
9条回答
  •  無奈伤痛
    2020-12-24 01:41

    I found a way... Although it's a bit hacky, and so there may be a better option.

    You'll need this package:

    import 'package:flutter/services.dart';
    

    Create the widget:

    class MyDialog extends StatefulWidget {
      MyDialog ({Key key}) : super(key: key);
      MyDialogState createState() => new MyDialogState();
    }
    class MyDialogState extends State {
    

    If the screen rotates it screws things up because the dialog maintains it's original size. You can probably fix that with a bit of effort, but I just lock it to prevent rotating, like this:

      @override
      initState() { super.initState();
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
      }
    

    Then I unlock it like this at the end:

      @override
      dispose() { super.dispose();
        SystemChrome.setPreferredOrientations([
          DeviceOrientation.landscapeRight,
          DeviceOrientation.landscapeLeft,
          DeviceOrientation.portraitUp,
          DeviceOrientation.portraitDown,
        ]);
      }
    

    So that stops the dialog from screwing up. Then I get the size and width of the screen in the build method:

    @override
    Widget build(BuildContext context) {
      double width = MediaQuery.of(context).size.width;
      double height = MediaQuery.of(context).size.height;
    

    Then followed with this layout:

     return ConstrainedBox(
        constraints: BoxConstraints(maxHeight: height, maxWidth: width),
        child: Column(
          children: [
            Expanded(
              child: GridView.count(
                primary: false,
                padding: const EdgeInsets.all(20.0),
                crossAxisSpacing: 10.0,
                crossAxisCount: 3,
                children: _images
              )
            ),
          ]
        ),
      );
    }
    

    ..again, I don't think it's the best, but it's been working for me so far.

提交回复
热议问题