Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
249 views
in Technique[技术] by (71.8m points)

flutter - Should you await Navigator calls in buttons

Considering that Navigator.of(context).push() returns a Future<void>, is it a good idea to be awaiting them inside of buttons?

IconButton(
  icon: Icon(Icons.search),
  onPressed: () => AutoRouter.of(context).push(
    SearchPageRoute(),
  ),
)

// -->

IconButton(
  icon: Icon(Icons.search),
  onPressed: () async {
    await Navigator.of(context).push(
      SearchPageRoute(),
    );
  },
)

Would it make any difference on a practical level? I'm asking because I recently made a AsyncButtonBuilder that handles the loading state and disabled state of buttons but am curious if Navigation operations would ever have the latency required to even show a loading indicator.

For example, is this next piece of code pointless considering Navigator is almost synchronous -- at least as it appears to me?

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  var isLoading = false;

  @override
  Widget build(BuildContext context) {
    return IconButton(
      icon: isLoading ? CircularProgressIndicator() : Icon(Icons.search),
      onPressed: isLoading
          ? null
          : () async {
              setState(() {
                isLoading = true;
              });
              await Navigator.of(context).push(SearchPageRoute());
              if (mounted) {
                setState(() {
                  isLoading = false;
                });
              }
            },
    );
  }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The reason why they have a future callback is because you can pass results back to the page where you push from. A good example will be pushing a dialog and waiting for a response from the user. This is where you use await to wait for the user input, then from what response the user selected it will return back to the first screen where you pushed it.

TLDR: if you don't need to wait for a response from a screen you don't need to include await.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...