searchfield icon indicating copy to clipboard operation
searchfield copied to clipboard

'package:flutter/src/widgets/overlay.dart': Failed assertion: line 207 pos 12: '_overlay != null': is not true.

Open shahmirzali49 opened this issue 3 years ago • 35 comments

Describe the bug A clear and concise description of what the bug is.

Unhandled Exception: Bad state: Cannot add new events after calling close

When I used second-time SearchField, I didn't know why it gave me this error.

sorry I don't have wide info about error.

edited: Issue reproduces with latest v0.9.9

minimal code sample
import 'package:flutter/material.dart';
import 'package:searchfield/searchfield.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Material App',
      home: BottomNavBarHome(),
    );
  }
}

class BottomNavBarHome extends StatefulWidget {
  const BottomNavBarHome({Key? key}) : super(key: key);

  @override
  State<BottomNavBarHome> createState() => _BottomNavBarHomeState();
}

class _BottomNavBarHomeState extends State<BottomNavBarHome> {
  late PageController _pageController;
  late final GlobalKey<State<BottomNavigationBar>> _bottomNavBarKey;
  DateTime? currentBackPressTime;
  @override
  void initState() {
    _pageController = PageController();
    _bottomNavBarKey = GlobalKey<State<BottomNavigationBar>>();
    super.initState();
  }

  int selectindex = 0;
  void _onItemTapped(int selectedIndex) {
    setState(() {
      selectindex = selectedIndex;
      _pageController.jumpToPage(selectindex);
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Scaffold(
        extendBody: true,
        body: PageView(
          controller: _pageController,
          children: [
            PageOne(
              bottomNavBarKey: _bottomNavBarKey,
            ),
            PageSecond(),
            PageThird(),
          ],
          // onPageChanged: _onPageChanged,
        ),
        bottomNavigationBar: BottomNavigationBar(
          currentIndex: selectindex,
          type: BottomNavigationBarType.fixed,
          key: _bottomNavBarKey,
          onTap: _onItemTapped,
          items: const [
            BottomNavigationBarItem(
              icon: Icon(Icons.home),
              label: 'Page 1',
              backgroundColor: Colors.blue,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.person),
              label: 'Page 2',
              backgroundColor: Colors.blue,
            ),
            BottomNavigationBarItem(
              icon: Icon(Icons.book),
              label: 'Page 3',
              backgroundColor: Colors.blue,
            ),
          ],
        ),
      ),
    );
  }
}

class PageOne extends StatefulWidget {
  const PageOne({Key? key, required this.bottomNavBarKey}) : super(key: key);

  final GlobalKey<State<BottomNavigationBar>> bottomNavBarKey;

  @override
  State<PageOne> createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  final List<String> _suggestions = [
    'United States',
    'Germany',
    'Washington',
    'Paris',
    'Jakarta',
    'Australia',
    'India',
    'Czech Republic',
    'Lorem Ipsum',
  ];

  BottomNavigationBar? bottomNavKey;

  @override
  Widget build(BuildContext context) {
    return Center(
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: SearchField(
          suggestionState: Suggestion.expand,
          suggestionAction: SuggestionAction.unfocus,
          suggestions: _suggestions.map((e) => SearchFieldListItem(e)).toList(),
          textInputAction: TextInputAction.done,
          hint: 'SearchField Example 1',
          autoCorrect: false,
          maxSuggestionsInViewPort: 3,
          itemHeight: 45,
          onSuggestionTap: (x) async {
            if (widget.bottomNavBarKey.currentWidget != null) {
              bottomNavKey =
                  widget.bottomNavBarKey.currentWidget as BottomNavigationBar;
            }
            bottomNavKey?.onTap!(1);
          },
        ),
      ),
    );
  }
}

class PageSecond extends StatelessWidget {
  const PageSecond({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(child: Text('Page Second')),
    );
  }
}

class PageThird extends StatelessWidget {
  const PageThird({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return const Scaffold(
      body: Center(
          child: Text(
        'Page Third',
      )),
    );
  }
}

logs
Restarted application in 1,876ms.
D/EGL_emulation( 6657): app_time_stats: avg=4548.26ms min=4548.26ms max=4548.26ms count=1
D/InputMethodManager( 6657): showSoftInput() view=io.flutter.embedding.android.FlutterView{6bfaeb4 VFE...... .F...... 0,0-1440,3064 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/InsetsController( 6657): show(ime(), fromIme=true)
D/EGL_emulation( 6657): app_time_stats: avg=11220.27ms min=5.66ms max=168162.59ms count=15
D/EGL_emulation( 6657): app_time_stats: avg=5991.23ms min=5991.23ms max=5991.23ms count=1
D/EGL_emulation( 6657): app_time_stats: avg=46.64ms min=5.86ms max=502.45ms count=22
D/EGL_emulation( 6657): app_time_stats: avg=314.47ms min=3.32ms max=6142.25ms count=20
D/EGL_emulation( 6657): app_time_stats: avg=5358.02ms min=5358.02ms max=5358.02ms count=1
D/InputMethodManager( 6657): showSoftInput() view=io.flutter.embedding.android.FlutterView{6bfaeb4 VFE...... .F...... 0,0-1440,3064 #1 aid=1073741824} flags=0 reason=SHOW_SOFT_INPUT
D/EGL_emulation( 6657): app_time_stats: avg=1785.92ms min=16.31ms max=8787.12ms count=5
D/InsetsController( 6657): show(ime(), fromIme=true)
D/EGL_emulation( 6657): app_time_stats: avg=613.65ms min=4.96ms max=9016.41ms count=15
D/EGL_emulation( 6657): app_time_stats: avg=66.43ms min=5.82ms max=505.28ms count=21
D/EGL_emulation( 6657): app_time_stats: avg=377.43ms min=140.98ms max=496.75ms count=3
D/EGL_emulation( 6657): app_time_stats: avg=715.01ms min=4.28ms max=13469.75ms count=19
D/EGL_emulation( 6657): app_time_stats: avg=1663.22ms min=11.73ms max=11548.72ms count=7

════════ Exception caught by widgets library ═══════════════════════════════════
The following assertion was thrown while finalizing the widget tree:
'package:flutter/src/widgets/overlay.dart': Failed assertion: line 207 pos 12: '_overlay != null': is not true.

When the exception was thrown, this was the stack:
#2      OverlayEntry.remove (package:flutter/src/widgets/overlay.dart:207:12)
#3      _SearchFieldState.dispose (package:searchfield/src/searchfield.dart:374:22)
#4      StatefulElement.unmount (package:flutter/src/widgets/framework.dart:5867:11)
#5      _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2097:13)
#6      _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#7      SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6940:14)
#8      _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#9      _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#10     SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6940:14)
#11     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#12     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#13     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#14     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#15     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#16     SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6940:14)
#17     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#18     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#19     SingleChildRenderObjectElement.visitChildren (package:flutter/src/widgets/framework.dart:6940:14)
#20     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#21     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#22     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#23     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#24     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#25     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#26     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#27     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#28     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#29     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#30     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#31     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#32     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#33     _InactiveElements._unmount.<anonymous closure> (package:flutter/src/widgets/framework.dart:2095:7)
#34     ComponentElement.visitChildren (package:flutter/src/widgets/framework.dart:5704:14)
#35     _InactiveElements._unmount (package:flutter/src/widgets/framework.dart:2093:13)
#36     ListIterable.forEach (dart:_internal/iterable.dart:49:13)
#37     _InactiveElements._unmountAll (package:flutter/src/widgets/framework.dart:2106:25)
#38     BuildOwner.lockState (package:flutter/src/widgets/framework.dart:2799:15)
#39     BuildOwner.finalizeTree (package:flutter/src/widgets/framework.dart:3234:7)
#40     WidgetsBinding.drawFrame (package:flutter/src/widgets/binding.dart:992:19)
#41     RendererBinding._handlePersistentFrameCallback (package:flutter/src/rendering/binding.dart:448:5)
#42     SchedulerBinding._invokeFrameCallback (package:flutter/src/scheduler/binding.dart:1386:15)
#43     SchedulerBinding.handleDrawFrame (package:flutter/src/scheduler/binding.dart:1311:9)
#44     SchedulerBinding._handleDrawFrame (package:flutter/src/scheduler/binding.dart:1169:5)
#45     _invoke (dart:ui/hooks.dart:312:13)
#46     PlatformDispatcher._drawFrame (dart:ui/platform_dispatcher.dart:399:5)
#47     _drawFrame (dart:ui/hooks.dart:283:31)
(elided 2 frames from class _AssertionError)
════════════════════════════════════════════════════════════════════════════════
D/EGL_emulation( 6657): app_time_stats: avg=31784.69ms min=31784.69ms max=31784.69ms count=1

shahmirzali49 avatar Aug 07 '22 21:08 shahmirzali49

when I click the error line in debug console.

Screen Shot 2022-08-08 at 01 32 06

shahmirzali49 avatar Aug 07 '22 21:08 shahmirzali49

my code

code
                          Form(
                              key: _soldierFormKey,
                              child: SearchField<FilterModel>(
                                suggestions: birthPlaceList
                                    .map(
                                      (e) => SearchFieldListItem<FilterModel>(e.title,
                                          item: e,
                                          child: Text(
                                            e.title,
                                            style: CustomTextStyles(context).headline5(
                                              fontWeight: FontWeight.normal,
                                              darkThemeColor: Colors.black,
                                              lightThemeColor: Colors.black,
                                            ),
                                          )),
                                    )
                                    .toList(),
                                suggestionState: Suggestion.expand,
                                textInputAction: TextInputAction.done,
                                hint: langTranslation!.search,
                                hasOverlay: false,
                                autoCorrect: false,
                                suggestionAction: SuggestionAction.unfocus,
                                searchStyle: CustomTextStyles(context).headline5(
                                  fontWeight: FontWeight.w500,
                                  darkThemeColor: Colors.black,
                                  lightThemeColor: Colors.black,
                                ),
                                validator: (validatorText) {
                                  if (validatorText != null && validatorText.isEmpty) {
                                    return null;
                                  } else if (validatorText != null &&
                                      !ref.read(containBirthPlaceProvider(validatorText))) {
                                    return "";
                                  } else if (validatorText != null &&
                                      ref.read(containBirthPlaceProvider(validatorText))) {
                                    int id = ref.read(getIdFromBirthPlaceListProvider(validatorText));
                                    placeId = id;
                                    print(" placeId $placeId ");
                                    ref.refresh(searchProvider).getSearchViewModel(
                                          soldierId: ref.refresh(soldierIdProvider.notifier).update((state) => 0),
                                          birthPlaceId: placeId,
                                        );
                                    ref.refresh(statusControlProvider.notifier).update((state) => null);

                                    bottomNavKey?.onTap!(1);
                                    return null;
                                  } else {
                                    return null;
                                  }
                                },
                                controller: _textEditingController,
                                searchInputDecoration: filterFormFieldDecoration(
                                  contentPaddingHorizontal: 20.w,
                                  contentPaddingVertical: 1.sm,
                                  context: context,
                                  errorBorderWidth: 2,
                                  suffixIcon: Row(
                                    mainAxisAlignment: MainAxisAlignment.end,
                                    mainAxisSize: MainAxisSize.min,
                                    children: [
                                      IconButton(
                                        splashColor: Colors.transparent,
                                        highlightColor: Colors.transparent,
                                        padding: EdgeInsets.zero,
                                        constraints: const BoxConstraints(minWidth: 1, minHeight: 1),
                                        splashRadius: 0.1,
                                        onPressed: () {
                                          
                                        },
                                        icon: const Icon(
                                          Icons.search,
                                          color: Colors.blue,
                                        ),
                                      ),
                                      IconButton(
                                        splashColor: Colors.transparent,
                                        highlightColor: Colors.transparent,
                                        splashRadius: 0.1,
                                        onPressed: () {
                                         
                                        },
                                        icon: const Icon(
                                          Icons.place_outlined,
                                          color: Colors.blue,
                                        ),
                                      ),
                                    ],
                                  ),
                                  errorStyle: const TextStyle(height: 0, color: Colors.transparent),
                                ),
                                onSubmit: (textValue) => _soldierFormKey.currentState?.validate(),
                                maxSuggestionsInViewPort: 3,
                                emptyWidget: Container(
                                  // height: 50,
                                  width: double.infinity,
                                  padding: EdgeInsets.only(
                                    top: 15.h,
                                    bottom: 15.h,
                                    left: 10.w,
                                  ),
                                  color: whiteColor,
                                  child: Text(
                                    langTranslation.noresult,
                                    style: CustomTextStyles(context).headline5(
                                      fontWeight: FontWeight.normal,
                                      darkThemeColor: Colors.black,
                                      lightThemeColor: Colors.black,
                                    ),
                                    // textAlign: TextAlign.center,
                                  ),
                                ),
                                itemHeight: 45.h,
                                onSuggestionTap: (SearchFieldListItem<FilterModel> value) {
                                  placeId = value.item?.id;
                                  _soldierFormKey.currentState?.validate();
                                },
                              ),
                            ),

shahmirzali49 avatar Aug 07 '22 21:08 shahmirzali49

HI @Shahmirzali-Huseynov, Thanks for filing the issue. Can you please try using fix-17 branch as mentioned here https://github.com/maheshmnj/searchfield/issues/17#issuecomment-1200108227 , I believe this issue is fixed.

maheshj01 avatar Aug 08 '22 03:08 maheshj01

Also see https://github.com/maheshmnj/searchfield/issues/17#issuecomment-1207684032

maheshj01 avatar Aug 08 '22 05:08 maheshj01

@maheshmnj thanks for replying, but I used 0.6.8 version of the package, but isn't fixed. the same error.

shahmirzali49 avatar Aug 08 '22 06:08 shahmirzali49

@maheshmnj Actually I noticed this error happen when I use GlobalKey for changing the page(index) of bottom nav. maybe this info will help you

bottomNavKey?.onTap!(1);

shahmirzali49 avatar Aug 08 '22 06:08 shahmirzali49

Thanks for the update @Shahmirzali-Huseynov, Can you please share a minimal and complete sample code? which I can directly run with minimal or no code changes. You may use the example app to share the reproducible code

maheshj01 avatar Aug 09 '22 05:08 maheshj01

I will, but unfortunately, I don't have time now, but I will try this week, and also I don't understand how the error is gone. but whatever I will do the minimal and complete sample code.

shahmirzali49 avatar Aug 09 '22 09:08 shahmirzali49

sure no worries take your time. And thank you so much for helping out to improve this package.

maheshj01 avatar Aug 09 '22 12:08 maheshj01

@maheshmnj sorry for the delay. this is the minimal and complete sample code.

flutter_searchfield_issue.zip

shahmirzali49 avatar Aug 29 '22 13:08 shahmirzali49

Thanks will take a look at it

maheshj01 avatar Aug 29 '22 15:08 maheshj01

@Shahmirzali-Huseynov Can you please explain what are the steps to reproduce the issue? I am unable to reproduce the error with your code sample. (I verified on macOS desktop app)

maheshj01 avatar Aug 30 '22 02:08 maheshj01

Can you also test with new release v0.7.0?

maheshj01 avatar Aug 30 '22 12:08 maheshj01

I tested but the problem is continuing. I share with you the screen record. Screen Recording 2022-08-30 at 17.02.36.zip

shahmirzali49 avatar Aug 30 '22 13:08 shahmirzali49

@Shahmirzali-Huseynov sorry for the delay please try version 0.7.1.

maheshj01 avatar Oct 07 '22 04:10 maheshj01

I tried but was not solved, again -> Screen Shot 2022-10-09 at 19 17 49

shahmirzali49 avatar Oct 09 '22 16:10 shahmirzali49

Thanks for the update @Shahmirzali-Huseynov Looks like the widget is getting disposed of because of the Global key, removing the code in didChangeDependencies doesn't reproduce the issue, Theres definetly something wrong, I 'll need to figure that out.

final GlobalKey<State<BottomNavigationBar>> bottomNavBarKey;

  @override
  void didChangeDependencies() {
    if (widget.bottomNavBarKey.currentWidget != null) {
      bottomNavKey =
          widget.bottomNavBarKey.currentWidget as BottomNavigationBar;
    }
    super.didChangeDependencies();
  }
code sample
import 'package:flutter/material.dart';
import 'package:searchfield/searchfield.dart';

class PageOne extends StatefulWidget {
  const PageOne({Key? key, required this.bottomNavBarKey}) : super(key: key);

  final GlobalKey<State<BottomNavigationBar>> bottomNavBarKey;

  @override
  State<PageOne> createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
  final List<String> _suggestions = [
    'United States',
    'Germany',
    'Washington',
    'Paris',
    'Jakarta',
    'Australia',
    'India',
    'Czech Republic',
    'Lorem Ipsum',
  ];

  BottomNavigationBar? bottomNavKey;

  @override
  void didChangeDependencies() {
    if (widget.bottomNavBarKey.currentWidget != null) {
      bottomNavKey =
          widget.bottomNavBarKey.currentWidget as BottomNavigationBar;
    }
    super.didChangeDependencies();
  }

  final _searchController = TextEditingController();
  final _formKey = GlobalKey<FormState>();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: ListView(
        children: <Widget>[
          const SizedBox(
            height: 100,
          ),
          Padding(
            padding: const EdgeInsets.all(8.0),
            child: SearchField(
              suggestionState: Suggestion.expand,
              suggestionAction: SuggestionAction.unfocus,
              suggestions:
                  _suggestions.map((e) => SearchFieldListItem(e)).toList(),
              textInputAction: TextInputAction.done,
              controller: _searchController,
              hint: 'SearchField Example 1',
              hasOverlay: false,
              autoCorrect: false,
              maxSuggestionsInViewPort: 3,
              itemHeight: 45,
              onSuggestionTap: (x) async {
                bottomNavKey?.onTap!(1);
              },
            ),
          ),
        ],
      ),
    );
  }
}

maheshj01 avatar Oct 10 '22 05:10 maheshj01

maybe the problem is in the function that runs or responds after the widget dispose.

shahmirzali49 avatar Oct 10 '22 07:10 shahmirzali49

@shahmirzali49 Could you please try the latest version of the plugin?

Thanks

maheshj01 avatar Mar 07 '24 00:03 maheshj01

Unfortunately, my project got old and I tried to run but there was an error I couldn't fix.

shahmirzali49 avatar Mar 07 '24 18:03 shahmirzali49

No worries, I am going to close this issue for now. In case you still encounter the issue please free to file a new issue and I would be happy to review

maheshj01 avatar Mar 08 '24 00:03 maheshj01

@maheshmnj sorry for the delay. this is the minimal and complete sample code.

flutter_searchfield_issue.zip

actually, if you want, you can test the issue

shahmirzali49 avatar Mar 12 '24 20:03 shahmirzali49

@maheshmnj sorry for the delay. this is the minimal and complete sample code.

flutter_searchfield_issue.zip

actually, if you want, you can test the issue

@shahmirzali49 is the bug still reproducible on the latest version of the package 0.9.7?

maheshj01 avatar Mar 12 '24 22:03 maheshj01

@maheshmnj I don't know. I just remembered I sent you minimal reproducible code. just a little reminder :)

shahmirzali49 avatar Mar 13 '24 00:03 shahmirzali49

No worries, thanks for the sample code I will take a look.

maheshj01 avatar Mar 13 '24 03:03 maheshj01

@shahmirzali49 The code is not downloadable can you please reupload?

maheshj01 avatar Mar 13 '24 03:03 maheshj01

sorry for the delay

flutter_searchfield_issue.zip

shahmirzali49 avatar Mar 19 '24 17:03 shahmirzali49

@shahmirzali49 I have updated the description of the issue, And looking at the logs it seems that this issue is potentially in flutter's overlay widget. Before we file it in flutter/flutter we might want to create a minimal reproducible sample without any third party package.

maheshj01 avatar Mar 20 '24 13:03 maheshj01

@shahmirzali49 I have filed the issue in flutter/flutter, I was able to reproduce it without the searchfield package. let's wait until it's triaged.

maheshj01 avatar Mar 20 '24 14:03 maheshj01

great 👍

shahmirzali49 avatar Mar 20 '24 16:03 shahmirzali49