Flutter use_build_context_synchronously and SearchDelegate.close after await

Viewed 395

My use case: I show a search UI the user can pick an item with - when the user taps an item, something async happens and depending on the result, close (https://api.flutter.dev/flutter/material/SearchDelegate/close.html) is called with either the picked item or a null. In my snippet below the async something is simply asking the user for confirmation with an AlertDialog.

This works without an issue but I updated the lint rules recently, and turned this one on: https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html. Now the linter complains about the BuildContext being used after an await in the call to close. Here is the snippet (full reproducible sample below, written with Flutter 2.10.4):

          onTap: () async {
            final confirmed = await _confirm(context, item) ?? false;
            // Triggers 'Do not use BuildContexts across async gaps.'
            // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
            close(context, confirmed ? item : null);
          },

I guess this makes sense and could be dangerous in some scenarios, so I'd better fix it. My question is: how do I implement my use case the 'right' way? One solution that works is to extract suggestions to a separate StatefulWidget and guard the call with a isMounted check, but this has the following drawbacks:

  • It requires a separate StatefulWidget that I would otherwise not need (boilerplate I don't want).
  • I need to pass a callback to the widget to call close (it belongs to SearchDelegate but now it will be called by code in the widget).
  • As close requires a BuildContext, I either have to pass the one that the SearchDelegate has to the widget to use (yuck) or just use the one from my widget - in this case it works (as close just uses Navigator.of(context)), but what if it were necessary to pass exactly the one from SearchDelegate?

Full code:

import 'package:flutter/material.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: _Home(),
    );
  }
}

class _Home extends StatefulWidget {
  @override
  State<_Home> createState() => _HomeState();
}

class _HomeState extends State<_Home> {
  String? _picked;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          TextButton(
            onPressed: () => _maybePick(context),
            child: const Text('Maybe pick'),
          ),
          Center(
            child: Text(_picked != null ? 'Last pick: $_picked' : 'No pick'),
          ),
        ],
      ),
    );
  }

  Future<void> _maybePick(BuildContext context) async {
    final result = await showSearch<String?>(
      context: context,
      delegate: _PickerDelegate(),
    );

    if (result != null) {
      setState(() {
        _picked = result;
      });
    }
  }
}

class _PickerDelegate extends SearchDelegate<String?> {
  final _allItems = List.generate(200, (index) => 'Item $index');

  @override
  Widget buildLeading(BuildContext context) {
    return IconButton(
      onPressed: () => close(context, null),
      icon: const BackButtonIcon(),
    );
  }

  @override
  List<Widget> buildActions(BuildContext context) {
    return [
      IconButton(
        onPressed: () => query = '',
        icon: const Icon(Icons.clear),
      ),
    ];
  }

  @override
  Widget buildSuggestions(BuildContext context) {
    final items = _allItems.where((element) => element.contains(query));

    return ListView(
      children: items.map((item) {
        return ListTile(
          title: Text(item),
          onTap: () async {
            final confirmed = await _confirm(context, item) ?? false;
            // Triggers 'Do not use BuildContexts across async gaps.'
            // https://dart-lang.github.io/linter/lints/use_build_context_synchronously.html
            close(context, confirmed ? item : null);
          },
        );
      }).toList(growable: false),
    );
  }

  @override
  Widget buildResults(BuildContext context) {
    // Keep it simple for the snippet.
    throw UnimplementedError('results are not supported');
  }

  Future<bool?> _confirm(BuildContext context, String item) async {
    return showDialog<bool>(
      context: context,
      builder: (context) {
        return AlertDialog(
          content: Text("Pick '$item'?"),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(true),
              child: const Text('Yes'),
            ),
            TextButton(
              onPressed: () => Navigator.of(context).pop(false),
              child: const Text('No'),
            ),
          ],
        );
      },
    );
  }
}
0 Answers
Related