flutter 关于使用showBottomSheet调用Widget时自动创建背景

6rqinv9w  于 2023-10-22  发布在  Flutter
关注(0)|答案(1)|浏览(121)

当在Flutter中使用showBottomSheet调用Widget时,会自动创建一个背景。我只想显示一个琥珀色的BottomSheetWidget,但会自动创建和显示蓝色背景。(为了清楚起见,我们指定color: Colors.blue,
如何在使用showBottomSheet调用Widget时删除自动创建的背景Widget?

DartPad

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(home: MyHomePage());
  }
}

class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});

  static final scaffoldKey = GlobalKey<ScaffoldState>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: TextButton(
              onPressed: () => showModalBottomSheet(
                  backgroundColor: Colors.blue,
                  context: context,
                  builder: (context) =>const BottomSheetWidget()),
              child: const Text('showBottomSheet'))),
    );
  }
}

class BottomSheetWidget extends StatelessWidget {
  const BottomSheetWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        width: 100,
        height: 300,
        color: Colors.amber,
      ),
    );
  }
}
bpsygsoo

bpsygsoo1#

你的代码很好,只需要在ModalBottomSheet中添加约束:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
          child: TextButton(
              onPressed: () => showModalBottomSheet(
                  backgroundColor: Colors.blue,
                  context: context,
                  constraints: const BoxConstraints(maxWidth:100), //THIS
                  builder: (context) =>const BottomSheetWidget()),
              child: const Text('showBottomSheet'))),
    );
  }
}

结果:

相关问题