如何在使用键盘时隐藏底部导航栏?

huangapple go评论92阅读模式
英文:

How to hide bottomNavigationBar when keyboard is used?

问题

我在使用Flutter,但底部导航栏(bottomNavigationBar)出现问题。我使用了一个名为GNav的底部导航栏,但是当我打开键盘进行搜索时,尽管设置了resizeToAvoidBottomInset: false属性,但我无法在不让底部导航栏保持在底部的情况下打开键盘。

以下是代码:

return MultiProvider(
      providers: [
        ChangeNotifierProvider<CRUDWords>.value(value: crudWords),
      ],
      child: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: PreferredSize(
          preferredSize: const Size.fromHeight(60.0), // 这里是期望的高度
          child: Container(
            decoration: const BoxDecoration(
              gradient: MyColors.primaryGradientColorTop,
              borderRadius: BorderRadius.only(
                bottomLeft: Radius.circular(30),
                bottomRight: Radius.circular(30),
              ),
            ),
            child: _setAppBar(),
          ),
        ),
        body: PageView(
          controller: _pageController,
          onPageChanged: (index) => onPageChanged(index),
          scrollDirection: Axis.horizontal,
          children: pages,
        ),

        // 浮动操作按钮
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            showMyBottomSheet(context, const AddWordPage());
          },
          backgroundColor: MyColors.primaryColor,
          shape: const RoundedRectangleBorder(
              borderRadius: BorderRadius.all(Radius.circular(16))),
          child: const Icon(Icons.add),
        ),

        // 底部导航栏
        bottomNavigationBar: Container(
          decoration: const BoxDecoration(
            gradient: MyColors.primaryGradientColorBottom,
            borderRadius: BorderRadius.only(
              topLeft: Radius.circular(30),
              topRight: Radius.circular(30),
            ),
          ),
          child: Padding(
            padding:
                const EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
            child: GNav(
              backgroundColor: Colors.transparent,
              color: Colors.white,
              activeColor: Colors.white,
              tabBackgroundColor: Colors.grey,
              gap: 8,
              padding: const EdgeInsets.all(16),
              tabs: _setNavigationDestination,
              selectedIndex: currentPage, // 更新选定的索引
              onTabChange: (index) {
                _pageController.animateToPage(
                  index,
                  duration: const Duration(milliseconds: 500),
                  curve: Curves.ease,
                );
                setState(() {
                  _activePage = currentPage;
                  currentPage = index; // 更新当前页面的索引
                  _bottomNavigationBarTapped = true;

                  // 用于页面3的动画
                  if (index != 2) {
                    globals.previousPage = index;
                  }
                });
                _setAppBarContent();
              },
            ),
          ),
        ),
      ),
    );
  }
}

我只想在打开键盘时保持底部导航栏在底部。

英文:

I'm on flutter, but I'm having a problem with the bottomNavigationBar. I use a GNav bottom bar, but when I open my keyboard to do a search, despite the resizeToAvoidBottomInset: false attribute, I can't open my keyboard without the bottom bar staying at the bottom.

Here is the code :

return MultiProvider(
providers: [
ChangeNotifierProvider&lt;CRUDWords&gt;.value(value: crudWords),
],
child: Scaffold(
resizeToAvoidBottomInset: false,
appBar: PreferredSize(
preferredSize: const Size.fromHeight(60.0), // here the desired height
child: Container(
decoration: const BoxDecoration(
gradient: MyColors.primaryGradientColorTop,
borderRadius: BorderRadius.only(
bottomLeft: Radius.circular(30),
bottomRight: Radius.circular(30),
),
),
child: _setAppBar(),
),
),
body: PageView(
controller: _pageController,
onPageChanged: (index) =&gt; onPageChanged(index),
scrollDirection: Axis.horizontal,
children: pages,
),
// floating action button
floatingActionButton: FloatingActionButton(
onPressed: () {
showMyBottomSheet(context, const AddWordPage());
},
backgroundColor: MyColors.primaryColor,
shape: const RoundedRectangleBorder(
borderRadius: BorderRadius.all(Radius.circular(16))),
child: const Icon(Icons.add),
),
// bottom navigation bar
bottomNavigationBar: Container(
decoration: const BoxDecoration(
gradient: MyColors.primaryGradientColorBottom,
borderRadius: BorderRadius.only(
topLeft: Radius.circular(30),
topRight: Radius.circular(30),
),
),
child: Padding(
padding:
const EdgeInsets.symmetric(horizontal: 15.0, vertical: 15.0),
child: GNav(
backgroundColor: Colors.transparent,
color: Colors.white,
activeColor: Colors.white,
tabBackgroundColor: Colors.grey,
gap: 8,
padding: const EdgeInsets.all(16),
tabs: _setNavigationDestination,
selectedIndex: currentPage, // mettre &#224; jour l&#39;index s&#233;lectionn&#233;
onTabChange: (index) {
_pageController.animateToPage(
index,
duration: const Duration(milliseconds: 500),
curve: Curves.ease,
);
setState(() {
_activePage = currentPage;
currentPage = index; // update the current page index
_bottomNavigationBarTapped = true;
// for animation in page 3
if (index != 2) {
globals.previousPage = index;
}
});
_setAppBarContent();
},
),
),
),
),
);
}
}

I just want to keep at the bottom the bottom bar whenever I open the keyboard.

答案1

得分: 0

你可以这样实现:

import 'package:flutter/material.dart';

class MyScreen extends StatefulWidget {
  @override
  _MyScreenState createState() => _MyScreenState();
}

class _MyScreenState extends State<MyScreen> with WidgetsBindingObserver {
  bool _isKeyboardVisible = false;

  @override
  void initState() {
    super.initState();
    // 将WidgetsBindingObserver添加到当前状态
    WidgetsBinding.instance.addObserver(this);
  }

  @override
  void dispose() {
    // 当状态被销毁时,移除WidgetsBindingObserver
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeMetrics() {
    // 当度量值改变时检查键盘的可见性
    final bottomInset = MediaQuery.of(context).viewInsets.bottom;
    setState(() {
      _isKeyboardVisible = bottomInset > 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('My Screen'),
      ),
      body: GestureDetector(
        onTap: () {
          // 点击文本框外部时关闭键盘
          FocusScope.of(context).unfocus();
        },
        child: SingleChildScrollView(
          child: Column(
            children: [
              TextField(
                decoration: InputDecoration(labelText: 'Text Field 1'),
              ),
              // 在此添加其他小部件
            ],
          ),
        ),
      ),
      bottomNavigationBar: _isKeyboardVisible
          ? null // 键盘可见时隐藏底部导航栏
          : Container(
              height: 100,
              color: Colors.red,
            ),
      // 在此添加底部导航栏项目
    );
  }
}
英文:

You can implement it this way:

 import &#39;package:flutter/material.dart&#39;;
class MyScreen extends StatefulWidget {
@override
_MyScreenState createState() =&gt; _MyScreenState();
}
class _MyScreenState extends State&lt;MyScreen&gt; with WidgetsBindingObserver {
bool _isKeyboardVisible = false;
@override
void initState() {
super.initState();
// Add the WidgetsBindingObserver to the current state
WidgetsBinding.instance.addObserver(this);
}
@override
void dispose() {
// Remove the WidgetsBindingObserver when the state is disposed
WidgetsBinding.instance.removeObserver(this);
super.dispose();
}
@override
void didChangeMetrics() {
// Check the keyboard visibility when the metrics change
final bottomInset = View.of(context).viewInsets.bottom;
setState(() {
_isKeyboardVisible = bottomInset &gt; 0;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(&#39;My Screen&#39;),
),
body: GestureDetector(
onTap: () {
// Dismiss the keyboard when tapping outside the text fields
FocusScope.of(context).unfocus();
},
child: SingleChildScrollView(
child: Column(
children: [
TextField(
decoration: InputDecoration(labelText: &#39;Text Field 1&#39;),
),
// Add your other widgets here
],
),
),
),
bottomNavigationBar: _isKeyboardVisible
? null // Hide the BottomNavigationBar when the keyboard is visible
: Container(
height: 100,
color: Colors.red,
),
// Add your BottomNavigationBar items here
);
}
}

huangapple
  • 本文由 发表于 2023年6月2日 05:00:04
  • 转载请务必保留本文链接:https://go.coder-hub.com/76385675.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定