最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - Keyboard instantly close when click on TextField - Stack Overflow

programmeradmin0浏览0评论

Whenever I click a text field, the keyboard opens for a split second and closes. There are no errors in the debug menu as well. I have a login page that is in development, and it has nothing but a TextFiled() empty widget. It's working fine.

How it worked: I removed key: scaffoldkey (but then drawer will not open)

Here is my HomePage file

import 'package:flutter/material.dart';
import 'package:resturant/constant.dart';
import 'package:resturant/widgets/items.dart';
import 'package:resturant/widgets/sidemenu.dart';
import 'package:resturant/widgets/welcome.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    TabController tabController = TabController(length: 3, vsync: this);
    var scaffoldkey = GlobalKey<ScaffoldState>();
    double devicewidth = MediaQuery.of(context).size.width;
    double deviceheight = MediaQuery.of(context).size.height;
    return PopScope(
      canPop: false,
      child: SafeArea(
          child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color(0xFFFFF5F5),
        key: scaffoldkey,
        drawer: const SideMenu(),
        appBar: AppBar(
          backgroundColor: const Color(0xFFFFF5F5),
          title: IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.shopping_cart_checkout_rounded,
              color: Color(0xffFF3A3A),
              size: 30,
            ),
          ),
          titleSpacing: devicewidth - 110,
          leading: IconButton(
            onPressed: () {
              scaffoldkey.currentState!.openDrawer();
            },
            icon: const Icon(
              Icons.menu_rounded,
              color: Color(0xffFF3A3A),
              size: 35,
            ),
          ),
          automaticallyImplyLeading: false,
        ),
        body: Column(
          children: [
            const Expanded(flex: 2, child: WelcomeWidget()),
            SizedBox(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(
                        left: defaultPadding + 10,
                        top: 8,
                        right: defaultPadding + 10),
                    child: TextField(
                      decoration: InputDecoration(
                          prefixIconColor: Color(0xFFFF6666),
                          filled: true,
                          fillColor: Color(0xFFFFDDDD),
                          prefixIcon: Icon(Icons.search),
                          hintText: 'Search Food',
                          hintStyle: TextStyle(color: Color(0xFFFF6666)),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          enabledBorder: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)))),
                    ),
                  ),
                  Padding(
                      padding: const EdgeInsets.only(bottom: 15),
                      child: TabBar(
                        padding: EdgeInsets.zero,
                        labelPadding: EdgeInsets.zero,
                        indicatorPadding: EdgeInsets.zero,
                        controller: tabController,
                        indicatorColor: const Color(0xffFF2B2B),
                        labelColor: const Color(0xffFF2B2B),
                        labelStyle:
                            const TextStyle(fontWeight: FontWeight.bold),
                        unselectedLabelColor: Colors.black,
                        tabs: const [
                          Tab(
                            text: 'Items',
                          ),
                          Tab(
                            text: 'Combos',
                          ),
                          Tab(
                            text: 'Deals',
                          ),
                        ],
                      ))
                ],
              ),
            ),

            // List of food items

            Expanded(
                flex: deviceheight > 830 ? 8 : 8,
                child: TabBarView(controller: tabController, children: [
                  const ItemsWidget(),
                  Container(
                    width: devicewidth,
                    color: Colors.yellow,
                  ),
                  Container(
                    width: devicewidth,
                    color: Colors.black,
                  )
                ])),
          ],
        ),
      )),
    );
  }
}

I don't know how I can make both work together the drawer open drawer and textfield. Can someone help me with this?

Whenever I click a text field, the keyboard opens for a split second and closes. There are no errors in the debug menu as well. I have a login page that is in development, and it has nothing but a TextFiled() empty widget. It's working fine.

How it worked: I removed key: scaffoldkey (but then drawer will not open)

Here is my HomePage file

import 'package:flutter/material.dart';
import 'package:resturant/constant.dart';
import 'package:resturant/widgets/items.dart';
import 'package:resturant/widgets/sidemenu.dart';
import 'package:resturant/widgets/welcome.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  @override
  Widget build(BuildContext context) {
    TabController tabController = TabController(length: 3, vsync: this);
    var scaffoldkey = GlobalKey<ScaffoldState>();
    double devicewidth = MediaQuery.of(context).size.width;
    double deviceheight = MediaQuery.of(context).size.height;
    return PopScope(
      canPop: false,
      child: SafeArea(
          child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color(0xFFFFF5F5),
        key: scaffoldkey,
        drawer: const SideMenu(),
        appBar: AppBar(
          backgroundColor: const Color(0xFFFFF5F5),
          title: IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.shopping_cart_checkout_rounded,
              color: Color(0xffFF3A3A),
              size: 30,
            ),
          ),
          titleSpacing: devicewidth - 110,
          leading: IconButton(
            onPressed: () {
              scaffoldkey.currentState!.openDrawer();
            },
            icon: const Icon(
              Icons.menu_rounded,
              color: Color(0xffFF3A3A),
              size: 35,
            ),
          ),
          automaticallyImplyLeading: false,
        ),
        body: Column(
          children: [
            const Expanded(flex: 2, child: WelcomeWidget()),
            SizedBox(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  const Padding(
                    padding: EdgeInsets.only(
                        left: defaultPadding + 10,
                        top: 8,
                        right: defaultPadding + 10),
                    child: TextField(
                      decoration: InputDecoration(
                          prefixIconColor: Color(0xFFFF6666),
                          filled: true,
                          fillColor: Color(0xFFFFDDDD),
                          prefixIcon: Icon(Icons.search),
                          hintText: 'Search Food',
                          hintStyle: TextStyle(color: Color(0xFFFF6666)),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          enabledBorder: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)))),
                    ),
                  ),
                  Padding(
                      padding: const EdgeInsets.only(bottom: 15),
                      child: TabBar(
                        padding: EdgeInsets.zero,
                        labelPadding: EdgeInsets.zero,
                        indicatorPadding: EdgeInsets.zero,
                        controller: tabController,
                        indicatorColor: const Color(0xffFF2B2B),
                        labelColor: const Color(0xffFF2B2B),
                        labelStyle:
                            const TextStyle(fontWeight: FontWeight.bold),
                        unselectedLabelColor: Colors.black,
                        tabs: const [
                          Tab(
                            text: 'Items',
                          ),
                          Tab(
                            text: 'Combos',
                          ),
                          Tab(
                            text: 'Deals',
                          ),
                        ],
                      ))
                ],
              ),
            ),

            // List of food items

            Expanded(
                flex: deviceheight > 830 ? 8 : 8,
                child: TabBarView(controller: tabController, children: [
                  const ItemsWidget(),
                  Container(
                    width: devicewidth,
                    color: Colors.yellow,
                  ),
                  Container(
                    width: devicewidth,
                    color: Colors.black,
                  )
                ])),
          ],
        ),
      )),
    );
  }
}

I don't know how I can make both work together the drawer open drawer and textfield. Can someone help me with this?

Share Improve this question asked Nov 20, 2024 at 5:21 Mr Prime TOMr Prime TO 131 silver badge2 bronze badges 2
  • resizeToAvoidBottomInset: true, This allows the screen to resize when the keyboard appears, preventing the immediate collapse of the keyboard after opening the TextField. – Visal Commented Nov 20, 2024 at 7:27
  • Hey, Check out my code I have explained the issue properly and resolved the drawer problem also. Please mark the answer as right, if it helps you. Thank you. – Sudip Mahanta Commented Nov 21, 2024 at 3:03
Add a comment  | 

3 Answers 3

Reset to default 0

scaffoldkey should not be initialized inside build, when keyboard is showing, build will be invoked, then created a new scaffoldkey, a new Scaffold, then keyboard will hide immediately, just move scaffoldkey outside like below

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {

  var scaffoldkey = GlobalKey<ScaffoldState>();

}

By making the scaffoldKey static, you ensure it is not recreated during widget rebuilds caused by the keyboard opening or closing. This stabilization prevents the issue of the keyboard unexpectedly closing

import 'package:flutter/material.dart';
import 'package:resturant/constant.dart';
import 'package:resturant/widgets/items.dart';
import 'package:resturant/widgets/sidemenu.dart';
import 'package:resturant/widgets/welcome.dart';

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
// make the scaffoldKey static
 static var scaffoldkey = GlobalKey<ScaffoldState>();
}

The issue occurs because the GlobalKey used for the Scaffold and the TextField is not being utilized properly to manage focus. When the TextField is tapped, the FocusNode loses focus, likely due to the widget rebuilding or interference from the GlobalKey handling.

TabController is not handled properly each time user focus on TextField TabController will re-initialised.

Updated Code:

class HomePage extends StatefulWidget {
  const HomePage({super.key});

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> with TickerProviderStateMixin {
  late TabController tabController;
  @override
  void initState() {
    tabController = TabController(length: 3, vsync: this);
    super.initState();
  }

  var scaffoldkey = GlobalKey<ScaffoldState>();

  double defaultPadding = 10;
  @override
  Widget build(BuildContext context) {
    double devicewidth = MediaQuery.of(context).size.width;
    double deviceheight = MediaQuery.of(context).size.height;
    return PopScope(
      canPop: false,
      child: SafeArea(
          child: Scaffold(
        resizeToAvoidBottomInset: false,
        backgroundColor: const Color(0xFFFFF5F5),
        key: scaffoldkey,
        drawer: const Drawer(
          width: 200,
          child: Text("jkndsfj"),
        ),
        appBar: AppBar(
          backgroundColor: const Color(0xFFFFF5F5),
          title: IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.shopping_cart_checkout_rounded,
              color: Color(0xffFF3A3A),
              size: 30,
            ),
          ),
          titleSpacing: devicewidth - 110,
          leading: IconButton(
            onPressed: () {
              scaffoldkey.currentState!.openDrawer();
            },
            icon: const Icon(
              Icons.menu_rounded,
              color: Color(0xffFF3A3A),
              size: 35,
            ),
          ),
          automaticallyImplyLeading: false,
        ),
        body: Column(
          children: [
            SizedBox(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Padding(
                    padding: EdgeInsets.only(
                        left: defaultPadding + 10,
                        top: 8,
                        right: defaultPadding + 10),
                    child: const TextField(
                      decoration: InputDecoration(
                          prefixIconColor: Color(0xFFFF6666),
                          filled: true,
                          fillColor: Color(0xFFFFDDDD),
                          prefixIcon: Icon(Icons.search),
                          hintText: 'Search Food',
                          hintStyle: TextStyle(color: Color(0xFFFF6666)),
                          focusedBorder: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          enabledBorder: OutlineInputBorder(
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)),
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0)),
                          border: OutlineInputBorder(
                              borderSide: BorderSide(
                                  color: Color(0xFFFFDDDD), width: 0),
                              borderRadius:
                                  BorderRadius.all(Radius.circular(8)))),
                    ),
                  ),
                  Padding(
                      padding: const EdgeInsets.only(bottom: 15),
                      child: TabBar(
                        padding: EdgeInsets.zero,
                        labelPadding: EdgeInsets.zero,
                        indicatorPadding: EdgeInsets.zero,
                        controller: tabController,
                        indicatorColor: const Color(0xffFF2B2B),
                        labelColor: const Color(0xffFF2B2B),
                        labelStyle:
                            const TextStyle(fontWeight: FontWeight.bold),
                        unselectedLabelColor: Colors.black,
                        tabs: const [
                          Tab(text: 'Items'),
                          Tab(text: 'Combos'),
                          Tab(text: 'Deals'),
                        ],
                      ))
                ],
              ),
            ),

            // List of food items

            Expanded(
                flex: deviceheight > 830 ? 8 : 8,
                child: TabBarView(controller: tabController, children: [
                  Container(
                    width: devicewidth,
                    color: Colors.blue,
                  ),
                  Container(
                    width: devicewidth,
                    color: Colors.yellow,
                  ),
                  Container(
                    width: devicewidth,
                    color: Colors.black,
                  )
                ])),
          ],
        ),
      )),
    );
  }
}
发布评论

评论列表(0)

  1. 暂无评论