0

I have a Stateless flutter widget which shows a list of TODOs. The list is shown using a ChangeNotifierProvider (of TodoList object, which contains a list of todos). Now when I load the page, I want to show a dialog box asking user to enter a new TODO if and only if the existing todos is empty. Inside the builder of the ChangeNotifierProvider, i tried below logic

if (todoList.todos.length == 0) {
    _showDialog(context);
    return Column...;
} else {
    return ListBuilder...;
}

But its showing 2 dialog box (probably due to the build method executing twice). I have to pass context to dialog box because I'm updating the todoList inside it, which should trigger a rebuild.

How do I handle this scenario. I've tried using flag (_isDialogOpen) but its not still working?

shahalpk
  • 3,383
  • 7
  • 36
  • 55

1 Answers1

0

make the widget Stateful in order to use it's lifecycle methods, you can use then initState() for showing the dialog when the page widgets are inserted in the widget tree, but you will need to use an addPostFrameCallback() to schedule showing it 1 frame after the initState's code gets executed:

First, import:

import package:flutter/scheduler.dart.

Then use this:

@override
void initState() {
  // ...
  SchedulerBinding.addPostFrameCallback((_) => _showDialog(context),);
}
Gwhyyy
  • 7,554
  • 3
  • 8
  • 35