skip to Main Content

So basically what happens is that I have a search screen, which within it I am using the keyboard as a part of the search. The search results are represented in a custom Card.
The moment the user press the card the app will change screen to a details screen for each result.
The moment the user has moved to the next screen, the keyboard stays OPENED.

Now, first thing first, I am well aware its a possible duplicate of this one

And I have already tried both options from there:

FocusScope.of(context).unfocus();
FocusManager.instance.primaryFocus?.unfocus();

Its worth mentioning I have tried to place these 2 options in several places: dispose method of the search screen, the on tap method of the card, in the init(bad idea) and/or build method of the details screen, wrapping the screens with gesture detector inside the on Tap ,and also in the actual tab of the details screen which has a bottom navigation bar which changes half of the screen to one tab from a tabs list. (Also stateful widgets, sort of like a fragment manager).

Relevant code (without the unfocus lines since it didn’t work properly in all the options I suggested) :

Search Screen

return Scaffold(
   backgroundColor: AppColors.backgroundColorHome,
   appBar: AppBar(
     backgroundColor: Colors.black,
        //**************************//
     title: AppSearchField(controller: _searchTextController, hint: "Search for Qyooz", isAutoFocused: true),
     actions: [
       Visibility(visible: _isTextFilled, child: IconButton(
           onPressed: (){
             setState(() {
               String _randomKey = DateTime.now().millisecond.toString();
                  _searchTextController.text = '';
                  _refreshKey = Key(_randomKey);
                });
              },
              icon: Icon(Icons.close, color: Colors.white70)
          )),
          Visibility(visible: _isTextFilled, child: IconButton(
              onPressed: (){
                _searchForQyooz();
              },
              icon: Icon(Icons.search, color: Colors.white70)
          ))
        ],
      ),
body: Container(
        padding: EdgeInsets.symmetric(vertical: AppSpacing.SPACEx2, horizontal: AppSpacing.SPACE),
        child: PaginationView<CallLog>(
            shrinkWrap: true,
            pullToRefresh: true,
            key: _refreshKey,
            preloadedItems: <CallLog>[],
            itemBuilder: (BuildContext innerCtx, CallLog _calledNumber, int index) {
              print('_calledNumber ==> ${_calledNumber.countryCode} ${_calledNumber.callNumber}');
              return CardQyooz(callLog: _calledNumber);
            },
            pageFetch: _getCallLogs,
            onError: (dynamic error) => Center(
              child: Text("$error", style: AppStyles.textStyleHeading(color: Colors.red, size: 16, weight: FontWeight.w400)),
            ),
            onEmpty: Center(
              child: Text("Please search for Qyooz", style: AppStyles.textStyleHeading(color: Colors.black54, size: 16, weight: FontWeight.w400)),
            ),
            bottomLoader: Center( // optional
              child: CircularProgressIndicator(color: Colors.purple),
            ),
            initialLoader: ListView( // optional
              shrinkWrap: true,
              physics: NeverScrollableScrollPhysics(),
              children: [
                ShimmerBlankQyooz(rating: 4.5),
                ShimmerBlankQyooz(rating: 2.7),
                ShimmerBlankQyooz(rating: 3),
                ShimmerBlankQyooz(rating: 2.7),
              ],
            )
        ),
      ),

Card – there is a lot more code, non relevant to the subject..

 return ConstrainedBox(
      constraints: BoxConstraints(
        minHeight: 170
      ),
      child: GestureDetector(
        onTap: (){
          FocusScope.of(context).unfocus();
          FocusManager.instance.primaryFocus?.unfocus();
          Get.to(() => ScreenQyoozDetails(callLog: widget.callLog));
        },

Details Screen

              _callLog.isEmpty == true
                  ? FutureBuilder(
                      future: _detectCallLog(),
                      builder: (innerCtx, snapshot) {
                        if (snapshot.hasData) {
                          FocusScope.of(context).unfocus();
                          FocusManager.instance.primaryFocus?.unfocus();
                          switch (_selectedTabIndex) {
                            case 3:
                              return TabHistory(callLog: _callLog);
                            case 2:
                              return TabServices(
                                  serviceCode: _serviceCode, callLog: _callLog);
                            case 1:
                              return TabFeed(
                                  key: _tabFeedKey,
                                  phoneNumber:
                                      '${_callLog.countryCode}${_callLog.callNumber}');
                            default:
                              return TabDashboard(callLog: _callLog);
                          }
                        } else if (snapshot.hasError) {
                          return Text('Error: ${snapshot.error.toString()}');
                        } else {
                          return Center(
                            child: CircularProgressIndicator(
                              color: Colors.purple,
                            ),
                          );
                        }
                      })
                  : Builder(builder: (innerCtx) {
                      switch (_selectedTabIndex) {
                        case 3:
                          return TabHistory(callLog: _callLog);
                        case 2:
                          return TabServices(
                              serviceCode: _serviceCode, callLog: _callLog);
                        case 1:
                          return TabFeed(
                              key: _tabFeedKey,
                              phoneNumber:
                                  '${_callLog.countryCode}${_callLog.callNumber}');
                        default:
                          return TabDashboard(callLog: _callLog);
                      }
                    }),

I wonder if there’s some kind of another problem in the code that prevents the keyboard from shutting off.

Thanks in advance.

2

Answers


  1. Chosen as BEST ANSWER

    So after lots of research and a 1000 checks on my code, I managed to figure it out. Apparently those that created the code at first used their own custom widget as the app bar search field. For some reason it didn't react to the unfocus methods mentioned above.

    What made the difference is changing this custom widget to have the option to change the autoFocus boolean(it was final at first).

    So, adding:

                widget.fld?.isAutoFocused = false;
    

    in the card onTap method, After it was true when the search field created at first, after passing the AppSearchField parameter from the Search Screen to the card, solved it.

    Hope it can help someone in the future, in case he's using a custom widget as the title of the app bar, and specifically as a search field.


  2. I ran into similar problem like this where keyboard was not closed on moving to next page , and I found a solution that worked for me not sure it its the correct way or it would work for you , but you can give it a try

     onTap: () async{
     Get.to(() => ScreenQyoozDetails(callLog: widget.callLog));
      await Future.delayed(const Duration(milliseconds: 100));
      FocusScope.of(context).unfocus();
      FocusManager.instance.primaryFocus?.unfocus();       
            },
    

    I think by adding this line await Future.delayed(const Duration(milliseconds: 100)); it gives time to the page to load and then it unfocuse the keyboard and before adding this line I think the code was being executed before page was loaded so the keyboard stayed in focus.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search