当在颤动中单击外部(父)时如何关闭子(小部件)?

时间:2019-11-05 16:08:15

标签: flutter flutter-layout flutter-widget

我有以下CupertinoPicker小部件:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import '../models/dropdown.dart';

class Dropdown extends StatefulWidget {
  final List<Item> items;

  const Dropdown({
    Key key,
    this.items,
  }) : super(key: key);

  @override
  _DropdownState createState() => _DropdownState();
}

class _DropdownState extends State<Dropdown> {
  bool _isModalActive = false;

  CupertinoPicker _cupertinoPicker() {
    return CupertinoPicker(
      looping: true,
      children: widget.items.map((item) => Text(item.label)).toList(),
      itemExtent: 35,
      onSelectedItemChanged: (_) {},
    );
  }

  void showModalBottomSheet(BuildContext context) {
    setState(() {
      _isModalActive = !_isModalActive;
    });

    _isModalActive
        ? showBottomSheet(
            context: context,
            builder: (context) => FractionallySizedBox(
              heightFactor: 0.3,
              child: _cupertinoPicker(),
            ),
          )
        : Navigator.pop(context);
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: () {
        showModalBottomSheet(context);
      },
      child: Container(
        width: double.infinity,
        padding: const EdgeInsets.all(0),
        height: 45,
        child: Text("Open"),
      ),
    );
  }
}

这是其中包含的屏幕:

import 'package:flutter/material.dart';
import './dropdown.dart';

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: GestureDetector(
        behavior: HitTestBehavior.translucent,
        onTap: () {},
        child: Container(
          padding: EdgeInsets.only(
              top: MediaQuery.of(context).padding.top, left: 15, right: 15),
          child: Dropdown(
            items: [
              Item(label: '2019', value: '2019'),
              Item(label: '2018', value: '2018'),
              Item(label: '2017', value: '2017'),
              Item(label: '2016', value: '2016'),
              Item(label: '2015', value: '2015'),
              Item(label: '2014', value: '2014'),
              Item(label: '2013', value: '2013'),
              Item(label: '2012', value: '2012'),
              Item(label: '2011', value: '2011'),
            ],
          ),
        ),
      ),
    );
  }
}

现在,在HomeScreen中的任意位置单击鼠标时,如何关闭下拉窗口小部件?我尝试在父级Navigator.pop(context)上进行onTap。它可以工作,但是很明显,当小部件关闭时,它会弹出到前一个屏幕。

对于这种行为是否存在可行的解决方案,即在父级的任意位置单击时关闭小部件?

0 个答案:

没有答案