How to Change State of Material Button after a Delay?

520 Views Asked by At

I have a List of Emojis, [, , , , , , , , , , , , , ] with me, I also have a Button With me with no Icon Associated with it. See this Material Button.

                     MaterialButton(
                        onPressed: () {},
                        
                        child: Text("",textScaleFactor: 2),
                        shape: CircleBorder(),
                        padding: EdgeInsets.all(16),
                      ),

Now, I need to Show up the Above list, [, , , , , , , , , , , , , ] after a Delay of 1 sec, inside this Button.

2

There are 2 best solutions below

0
On

You can use Timer.periodic to achieve this. See this sample code

Link to docs


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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Timer emojiTimer;

  @override
  void initState() {
    emojiTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      changeEmoji();
    });
    super.initState();
  }

  int randomInt = 0;
  Future<void> changeEmoji() async {
    setState(() {
      var ran = Random();
      randomInt = ran.nextInt(emojiList.length);
    });
  }

  var emojiList = [
    "",
    "",
    " ",
    "",
    " ",
    " ",
    "",
    "",
    "",
    "",
    "",
    "",
    "",
    ""
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Text('hello there'),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          emojiTimer.cancel();
        },
        child: Text(emojiList[randomInt]),
      ),
    );
  }
}

2
On

You can also use Future.

MaterialButton(
 onPressed: () async {
     await Future<void>.delayed(Duration(seconds: 1));
     // your function
     },
 child: Text('', textScaleFactor: 2),
 shape: CircleBorder(),
 padding: EdgeInsets.all(16),
),