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

bas*_*imm 7 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"),
            )
          ]),
        ),
      ),
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*ano 12

颤振 1.0,飞镖 2.x

此解决方案适用于StatelessWidget小部件和StatefulWidget小部件。

在顶部,在您的声明中,您可以创建一个 static 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();
}
Run Code Online (Sandbox Code Playgroud)

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

return MaterialApp(
        navigatorKey:MyApp.navKey,
        title: widget.title,
        ...
Run Code Online (Sandbox Code Playgroud)

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

@override
  void initState() {
  final context = MyApp.navKey.currentState.overlay.context;
  showMyCustomDialog(context);
  ...
  super.initState();
}
Run Code Online (Sandbox Code Playgroud)


anm*_*ail 5

为了修复错误。您需要将Call MainClass作为Home参数,MaterialApp如Like Like。

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

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

Main并将您的Build方法在Class中更新为:

@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"),
        )
      ]),
    );
  }
Run Code Online (Sandbox Code Playgroud)

  • 但您没有解释原因...原因是您在“Main”应用程序中收到的“context”参数位于“MaterialApp”小部件之上,这是对话框使用的上下文,因此任何对“Localizations.localeOf(context)”的搜索都将从“​​MaterialApp”上方开始搜索,“MaterialApp”是设置本地化的小部件。实际上,解决此问题的另一种方法是在两者之间放置一个“Builder”小部件。 (7认同)