Search code examples
flutterwidgetdelay

Flutter: How to add a widget inside a column which already has some widgets after 10 min


I want to draw three widgets inside a column but first widget to be drawn after 10 min. {Edit: After getting answer from Nickname i tried Timer.duration but it throws error: The method 'Timer' isn't defined for the type '_MainScreenState'. Try correcting the name to the name of an existing method, or defining a method named 'Timer'. What should i do now} Thank you

class MainScreenPortraitPageUI extends StatefulWidget {
  @override
  _MainScreenState createState() => _MainScreenState();
}

class _MainScreenState extends State<MainScreenPortraitPageUI> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("App title goes here")),
      body: Column(
        children: [
          Text('I want this widget to be drawn after some delay),
          Text("Second widget"),
          Text("Third widget"),
        ],
      ),
    );
  }
}


Solution

  • Try something like this. The idea is: -you set a local variable that controls if your Text is drawn or not (true/false). -in init state setup the timer that will after 10 minutes flip the variable to true. It will also call setState(), so your screen will be rebuilt.

    (I didn't try to compile this, so it could throw some errors on the first try):

    class MainScreenPortraitPageUI extends StatefulWidget {
      @override
      _MainScreenState createState() => _MainScreenState();
    }
    
    class _MainScreenState extends State<MainScreenPortraitPageUI> {
    
      bool drawFirstWidget=false;
    
    @override
    void initState() {
        super.initState();
        Timer(Duration(minutes: 10), () {
    setState(() {drawFirstWidget=true});
    });
    }
    
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(title: Text("App title goes here")),
          body: Column(
            children: [
              if (drawFirstWidget) Text('I want this widget to be drawn after some delay'),
              Text("Second widget"),
              Text("Third widget"),
            ],
          ),
        );
      }
    }