【问题标题】:Back button inside a TextFieldTextField 内的后退按钮
【发布时间】:2023-03-22 23:25:02
【问题描述】:

我想在 TextField 中有一个按钮,允许用户返回上一页。

我认为有两种不同的方法可以做到这一点:

  • 将按钮堆叠在 TextField 上方

  • 或者使用prefixIcon将按钮放置在TextField中

很遗憾,我无法以令人满意的方式实施这两种情况。

prefixIcon 方法:

  • 我得到了想要的按钮位置

  • 但是,当用户点击按钮时,键盘会自动弹起几分之一秒,然后立即关闭。

TextField(
  decoration: new InputDecoration(
    prefixIcon: IconButton(
      onPressed: () {
        Navigator.of(context).pop();
      },
      icon: Icon(
        IconData(58848,
            fontFamily: 'MaterialIcons',
            matchTextDirection: true),
        size: 30,
        color: Colors.orange.withOpacity(1.0),
      ),
    ),
    labelText: "Search",
    labelStyle: TextStyle(fontSize: 20),
    contentPadding:
        EdgeInsets.symmetric(horizontal: 70.0, vertical: 10.0),
  ),
  controller: _searchTextController,
),

堆栈方法:

  • 当用户点击后退按钮时,键盘不弹出

  • 如果没有直观地接近其位置,我无法将按钮与文本对齐(这会影响响应式设计)

Stack(
  children: [
    TextField(
      decoration: new InputDecoration(
        labelText: "Search",
        labelStyle: TextStyle(fontSize: 20),
        contentPadding: EdgeInsets.symmetric(
            horizontal: 70.0, vertical: 10.0),
      ),
      controller: _searchTextController,
      // onChanged: (String val) => _filterWith(val),
    ),
    IconButton(
      onPressed: () {
        Navigator.of(context).pop();
      },
      icon: Icon(
        IconData(58848,
            fontFamily: 'MaterialIcons',
            matchTextDirection: true),
        size: 30,
        color: Colors.orange.withOpacity(1.0),
      ),
    ),
  ],
),

有什么想法吗?

【问题讨论】:

  • 您可以尝试将 TextField 切换为 CupertinoTextField 吗?那会发生什么? (也就是说,如果你对这个不同的没问题)
  • 对于第二种方法,我使用AnimatedControllerreverseforward 在我的项目中实现它。但是,纠正位置和行为需要一些工作。

标签: flutter flutter-layout


【解决方案1】:

根据我对您的需求的理解,stack 方法似乎实现了所需的交互,但在视觉上是不正确的。我建议使用如下所示的 Positioned & Align 小部件封装您的 IconButton:

Stack(
  children: [
    TextField(
      decoration: new InputDecoration(
        labelText: "Search",
        labelStyle: TextStyle(fontSize: 20),
        contentPadding: EdgeInsets.symmetric(
            horizontal: 70.0, vertical: 10.0),
      ),
      controller: _searchTextController,
      // onChanged: (String val) => _filterWith(val),
    ),


    new Positioned ( child: new Align(
                       alignment: FractionalOffset.centerLeft,
                       child: 


    IconButton(
      onPressed: () {
        Navigator.of(context).pop();
      },
      icon: Icon(
        IconData(58848,
            fontFamily: 'MaterialIcons',
            matchTextDirection: true),
        size: 30,
        color: Colors.orange.withOpacity(1.0),
      ),
    ) // IconButton


    ), // align
   ), // Positioned  

  ],
),

也许还需要对 Padding Widget 进行一些调整。但是你应该能够实现你的目标。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-02-08
    • 2020-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-01
    • 1970-01-01
    相关资源
    最近更新 更多