When doing a one-time read, do you put the query in the Widget build() or higher up in the class?

Issue

I’m still a little unsure about code structure when building a flutter app so I want to make sure I understand how this part should work. For my notifications screen, I want to do a simple one-time read. If the user wants to get the latest notifs, they will back out and go back in.

In the code below, I’m running the query (that returns a Future<List>) outside of the Widget build(... section. What would be the difference if I were to put it in the Widget build(... section? What is the recommended thing to do here for a simple one-time read?

class _NotificationsState extends State<Notifications> {
  final database = Database();
  late final tempNotifsList = database.getNotifications();
  var notifsList;

  @override
  void initState() {
    super.initState();
    setState(() {
      notifsList = tempNotifsList;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // ...use the notifsList data...

Solution

States (and their variables) persist and they are initialized only once. As your query is a one-time read, put it in something that’s called once, like initState or the variable declarations.

Don’t put it in build:

This method can potentially be called in every frame and should not
have any side effects beyond building a widget.

Answered By – Banana

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *