Home > OS >  Flutter: Show AlertDialog when app is startup
Flutter: Show AlertDialog when app is startup

Time:10-08

I need help with my app. I want to get alertdialog when app is startup. I tried almost everything but nothing is alright. It still throws away similar errors. If I tried in other screens, everything is OK, but in main.dart isnt alright. I tried Stateless:

@override
  Widget build(BuildContext context) {
    Future.delayed(Duration.zero, () => showAlert(context));

and Stateful:

 class _MyAppState extends State<MyApp> {
      void initState() {
      super.initState();
      WidgetsBinding.instance?.addPostFrameCallback((_)
......

    class _MyAppState extends State<MyApp> {
        void initState() {
        super.initState(); 
        Future(_showDialog);
        Timer.run(_showDialog); // Requires import: 'dart:async'
      }

and others codes from web.

Errors:

> Reload already in progress, ignoring request
Restarted application in 3 059ms.
E/flutter (19353): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: No MaterialLocalizations found.
E/flutter (19353): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
E/flutter (19353): The material library uses Localizations to generate messages, labels, and abbreviations.
E/flutter (19353): To introduce a MaterialLocalizations, either use a MaterialApp at the root of your application to include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
E/flutter (19353): The specific widget that could not find a MaterialLocalizations ancestor was:
E/flutter (19353):   MyApp
E/flutter (19353): The ancestors of this widget were:
E/flutter (19353):   [root]
E/flutter (19353): #0      debugCheckHasMaterialLocalizations.<anonymous closure>
E/flutter (19353): #1      debugCheckHasMaterialLocalizations
E/flutter (19353): #2      showDialog
E/flutter (19353): #3      _MyAppState.initState.<anonymous closure>
E/flutter (19353): #4      _MyAppState.initState.<anonymous closure>
E/flutter (19353): #5      SchedulerBinding._invokeFrameCallback
E/flutter (19353): #6      SchedulerBinding.handleDrawFrame
E/flutter (19353): #7      SchedulerBinding.scheduleWarmUpFrame.<anonymous closure>
E/flutter (19353): #8      _rootRun (dart:async/zone.dart:1420:47)
E/flutter (19353): #9      _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (19353): #10     _CustomZone.runGuarded (dart:async/zone.dart:1236:7)
E/flutter (19353): #11     _CustomZone.bindCallbackGuarded.<anonymous closure> (dart:async/zone.dart:1276:23)
E/flutter (19353): #12     _rootRun (dart:async/zone.dart:1428:13)
E/flutter (19353): #13     _CustomZone.run (dart:async/zone.dart:1328:19)
E/flutter (19353): #14     _CustomZone.bindCallback.<anonymous closure> (dart:async/zone.dart:1260:23)
E/flutter (19353): #15     Timer._createTimer.<anonymous closure> (dart:async-patch/timer_patch.dart:18:15)
E/flutter (19353): #16     _Timer._runTimers (dart:isolate-patch/timer_impl.dart:395:19)
E/flutter (19353): #17     _Timer._handleMessage (dart:isolate-patch/timer_impl.dart:426:5)
E/flutter (19353): #18     _RawReceivePortImpl._handleMessage (dart:isolate-patch/isolate_patch.dart:192:12)
E/flutter (19353):

I don't know what to do anymore. Thank you very much for your information.

CodePudding user response:

Write this code in initState

WidgetsBinding.instance.addPostFrameCallback((_) async {
      await showDialog(
        context: context,
        builder: (BuildContext context) => Center(
          child: AlertDialog(
            insetPadding: EdgeInsets.all(20),
            contentPadding: EdgeInsets.all(0),
            content: Container(
              height: 200,
              width: MediaQuery.of(context).size.width,
            ),
            actions: <Widget>[],
          ),
        ),
      );
    });

Here is the full source code:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      await showDialog(
        context: context,
        builder: (BuildContext context) => Center(
          child: AlertDialog(
            insetPadding: EdgeInsets.all(20),
            contentPadding: EdgeInsets.all(0),
            content: Container(
              height: 200,
              width: MediaQuery.of(context).size.width,
              child: Center(
                child: Text("Alert dialog in app start up"),
              ),
            ),
            actions: <Widget>[],
          ),
        ),
      );
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      body: SafeArea(
        child: Container(),
      ),
    );
  }
}

Output:

enter image description here

CodePudding user response:

Did you provide the MaterialApp() widget as the entry to your app?

From the error info, it seems you are calling your widgets directly without this implementation of the MaterialApp widget. the _showDialog method works with this widget so you need to provide the MaterialApp as the entry, usually like this:

// your runapp function like this

runApp(MyApp());

class MyApp extends StatelessWidget {
   return MaterialApp(
     child: SplashScreen(), //or some other screens you would like to show
);

then you can be sure that your code will work.
  • Related