Flutter => showDialog / AlertDialog =>找不到MaterialLocalizations

时间:2019-01-04 08:09:11

标签: flutter

对于Flutter来说是新手,但印象深刻。 我想显示一个对话框,如果通过Firebase“ onMessage”到达PushNotification。

但是每次我得到一个异常“找不到MaterialLocalizations”。如果试图显示我的对话框。 为了进行测试,我添加了一个RaisedButton来显示此警报,但是同样的问题。 也许有人可以帮助我。 非常感谢!!!

这是小应用程序的全部代码:

import 'dart:async';

import 'package:firebase_messaging/firebase_messaging.dart';

import 'package:flutter/material.dart';

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

class Main extends StatefulWidget {
  @override
  _MainState createState() => _MainState();
}

class _MainState extends State<Main> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();

  Widget _buildDialog(BuildContext context) {
    print("_buildDialog");
    return AlertDialog(
      content: Text("Item  has been updated"),
      actions: <Widget>[
        FlatButton(
          child: const Text('CLOSE'),
          onPressed: () {
            Navigator.pop(context, false);
          },
        ),
        FlatButton(
          child: const Text('SHOW'),
          onPressed: () {
            Navigator.pop(context, true);
          },
        ),
      ],
    );
  }

  void _showPushDialog() {
    print("DIALOG");
    showDialog<bool>(
      context: context,
      builder: (_) => _buildDialog(context),
    ).then((bool shouldNavigate) {
      if (shouldNavigate == true) {
        _navigateToPushDetail();
      }
    });
  }

  void _navigateToPushDetail() {
    print("TODO: Goto...");
  }

  @override
  void initState() {
    super.initState();
    _firebaseMessaging.configure(
      onMessage: (Map<String, dynamic> message) async {
        print("onMessage: $message");
        //_neverSatisfied();
        _showPushDialog();
      },
      onLaunch: (Map<String, dynamic> message) async {
        print("onLaunch: $message");
        _navigateToPushDetail();
      },
      onResume: (Map<String, dynamic> message) async {
        print("onResume: $message");
        _navigateToPushDetail();
      },
    );

    _firebaseMessaging.requestNotificationPermissions(
        const IosNotificationSettings(sound: true, badge: true, alert: true));
    _firebaseMessaging.onIosSettingsRegistered
        .listen((IosNotificationSettings settings) {
      print("Settings registered: $settings");
    });
    _firebaseMessaging.getToken().then((String token) {
      assert(token != null);
      print("Push Messaging token: $token");
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Welcome to Flutter'),
        ),
        body: new Material(
          child: Column(children: <Widget>[
            Center(
              child: Text('Hello World'),
            ),
            RaisedButton(
              onPressed: () {
                print("pushed?");
                _showPushDialog();
              },
              child: Text("press me"),
            )
          ]),
        ),
      ),
    );
  }
}

3 个答案:

答案 0 :(得分:4)

为了修复错误。您需要调用Main类作为MaterialApp的home参数,如下所示。

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Welcome to Flutter',
      debugShowCheckedModeBanner: false,
      home: Main(),
    );
  }
}

并将您在Main类中的构建方法更新为:

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Welcome to Flutter'),
      ),
      body: Column(children: <Widget>[
        Center(
          child: Text('Hello World'),
        ),
        RaisedButton(
          onPressed: () {
            print("pushed?");
            _showPushDialog(context);
          },
          child: Text("press me"),
        )
      ]),
    );
  }

答案 1 :(得分:0)

Flutter 1.0,Dart 2.x

此解决方案在StatelessWidget小部件和StatefulWidget小部件上均适用。

在顶部的声明中,您可以创建一个静态的navKey

class MyApp extends StatefulWidget {
  final String title; // sample var you want to pass to your widget
  static final navKey = new GlobalKey<NavigatorState>();
  const MyApp({Key navKey, this.title}) : super(key: navKey);
  @override
  State<StatefulWidget> createState() => _MyAppState();
}

在布局部分,您应该使用按键:

return MaterialApp(
        navigatorKey:MyApp.navKey,
        title: widget.title,
        ...

因此,当您需要对话框或其他小部件的当前上下文时,可以在状态部分中进行操作:

@override
  void initState() {
  final context = MyApp.navKey.currentState.overlay.context;
  showMyCustomDialog(context);
  ...
  super.initState();
}

答案 2 :(得分:0)

检查您的MaterialApp()小部件, 如果您设置localizationsDelegates,可能会遇到此问题。 当我删除这些代码时,它会起作用。

              localizationsDelegates: [
                  DefaultCupertinoLocalizations.delegate,
              ],

我的代码。

MaterialApp(
              navigatorKey: navigatorKey,
              title: 'test',
              theme: ThemeData(
                  platform: TargetPlatform.iOS,
                  backgroundColor: Color(0xfff1f1f1),
                  accentColor: AppStyle.colorPrimary,
                  primaryColor: AppStyle.colorPrimary,
                  buttonColor: AppStyle.colorPrimary,
                  iconTheme: IconThemeData(color: Colors.white),
                  textTheme: TextTheme(
                      title: TextStyle(color: Colors.white),
                  ),
                  primaryTextTheme: TextTheme(title: TextStyle(color: Colors.white)),
                  primaryIconTheme: const IconThemeData.fallback().copyWith(
                      color: Colors.white,
                  ),
                  appBarTheme: AppBarTheme().copyWith(brightness: Brightness.dark),
              ),
              home: LoginPage(),
              debugShowCheckedModeBanner: false,
              onGenerateRoute: AppRouter.router.generator,
          )