How to perform an action after first frame in flutter

Sometimes, you might need to perform an action after the app’s first frame. Maybe, you want the Bottom Navbar to pop up immediately after the first frame. This is an example on how to handle just that.

Import the after_layout package from pub.

pubspec.yaml

after_layout: any

Create a new dart file and add this:

import 'package:after_layout/after_layout.dart';
import 'package:flutter/material.dart';

class ActionAfterFirstFrame extends StatefulWidget {
  @override
  _ActionAfterFirstFrameState createState() => _ActionAfterFirstFrameState();
}

class _ActionAfterFirstFrameState extends State<ActionAfterFirstFrame>
    with AfterLayoutMixin<ActionAfterFirstFrame> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Action after frist Frame Example')),
      body: Center(child: Text('Inducesmile.com')),
    );
  }

  @override
  void afterFirstLayout(BuildContext context) {
    _showMyDialog();
  }

  void _showMyDialog() {
    showDialog(
        context: context,
        builder: (context) => new AlertDialog(
              content: Text('Inducesmile.com'),
              actions: <Widget>[
                new FlatButton(
                  child: Text('Dismiss'),
                  onPressed: () => Navigator.of(context).pop(),
                )
              ],
            ));
  }
}

Your main.dart:

void main() => runApp(new MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Code Snippets',
      theme: new ThemeData(primarySwatch: Colors.red),
      home: new ActionAfterFirstFrame(),
    );
  }
}

Add a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.