找不到MaterialLocalizations-MyApp小部件要求MaterialLocalizations由Localizations小部件祖先提供

时间:2019-05-23 12:47:45

标签: android dart flutter

我只是试图创建一个带有按钮的应用程序,当按下按钮时会显示一条警告消息。

但是它给了我这个错误(下面提到)。

我通过参考this视频来编写此代码。

我正在使用adb connect在实时Android手机上运行应用程序

请帮助..!

代码

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Test",
      home: Scaffold(
        appBar: AppBar(title: Text("Test")),
        body: Container(
          child: Center(
            child: RaisedButton(
              color: Colors.redAccent,
              textColor: Colors.white,
              onPressed: (){testAlert(context);},
              child: Text("PressMe"),
            ),
          ),
        ),
      ),
    );
  }
  void testAlert(BuildContext context){
    var alert = AlertDialog(
      title: Text("Test"),
      content: Text("Done..!"),
    );

    showDialog(
        context: context,
        builder: (BuildContext context){
          return alert;
        }
    );
  }
}

这是我编写的代码。我还尝试将testAlert()函数的内容直接插入onPressed,但不起作用。

错误

Performing hot reload...
Syncing files to device ZUK Z2131...
Reloaded 0 of 419 libraries in 1,929ms.
I/flutter (18652): ══╡ EXCEPTION CAUGHT BY GESTURE ╞═══════════════════════════════════════════════════════════════════
I/flutter (18652): The following assertion was thrown while handling a gesture:
I/flutter (18652): No MaterialLocalizations found.
I/flutter (18652): MyApp widgets require MaterialLocalizations to be provided by a Localizations widget ancestor.
I/flutter (18652): Localizations are used to generate many different messages, labels,and abbreviations which are used
I/flutter (18652): by the material library. 
I/flutter (18652): To introduce a MaterialLocalizations, either use a  MaterialApp at the root of your application to
I/flutter (18652): include them automatically, or add a Localization widget with a MaterialLocalizations delegate.
I/flutter (18652): The specific widget that could not find a MaterialLocalizations ancestor was:
I/flutter (18652):   MyApp
I/flutter (18652): The ancestors of this widget were:
I/flutter (18652):   [root]
I/flutter (18652): 
I/flutter (18652): When the exception was thrown, this was the stack:
I/flutter (18652): #0      debugCheckHasMaterialLocalizations.<anonymous closure> (package:flutter/src/material/debug.dart:124:7)
I/flutter (18652): #1      debugCheckHasMaterialLocalizations (package:flutter/src/material/debug.dart:127:4)
I/flutter (18652): #2      showDialog (package:flutter/src/material/dialog.dart:635:10)
I/flutter (18652): #3      MyApp.testAlert (package:flutter_app/main.dart:33:5)
I/flutter (18652): #4      MyApp.build.<anonymous closure> (package:flutter_app/main.dart:19:29)
I/flutter (18652): #5      _InkResponseState._handleTap (package:flutter/src/material/ink_well.dart:507:14)
I/flutter (18652): #6      _InkResponseState.build.<anonymous closure> (package:flutter/src/material/ink_well.dart:562:30)
I/flutter (18652): #7      GestureRecognizer.invokeCallback (package:flutter/src/gestures/recognizer.dart:102:24)
I/flutter (18652): #8      TapGestureRecognizer._checkUp (package:flutter/src/gestures/tap.dart:242:9)
I/flutter (18652): #9      TapGestureRecognizer.handlePrimaryPointer (package:flutter/src/gestures/tap.dart:175:7)
I/flutter (18652): #10     PrimaryPointerGestureRecognizer.handleEvent (package:flutter/src/gestures/recognizer.dart:315:9)
I/flutter (18652): #11     PointerRouter._dispatch (package:flutter/src/gestures/pointer_router.dart:73:12)
I/flutter (18652): #12     PointerRouter.route (package:flutter/src/gestures/pointer_router.dart:101:11)
I/flutter (18652): #13     _WidgetsFlutterBinding&BindingBase&GestureBinding.handleEvent (package:flutter/src/gestures/binding.dart:180:19)
I/flutter (18652): #14     _WidgetsFlutterBinding&BindingBase&GestureBinding.dispatchEvent (package:flutter/src/gestures/binding.dart:158:22)
I/flutter (18652): #15     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerEvent (package:flutter/src/gestures/binding.dart:138:7)
I/flutter (18652): #16     _WidgetsFlutterBinding&BindingBase&GestureBinding._flushPointerEventQueue (package:flutter/src/gestures/binding.dart:101:7)
I/flutter (18652): #17     _WidgetsFlutterBinding&BindingBase&GestureBinding._handlePointerDataPacket (package:flutter/src/gestures/binding.dart:85:7)
I/flutter (18652): #18     _invoke1 (dart:ui/hooks.dart:168:13)
I/flutter (18652): #19     _dispatchPointerDataPacket (dart:ui/hooks.dart:122:5)
I/flutter (18652): 
I/flutter (18652): Handler: onTap
I/flutter (18652): Recognizer:
I/flutter (18652):   TapGestureRecognizer#d5d82(debugOwner: GestureDetector, state: possible, won arena, finalPosition:
I/flutter (18652):   Offset(220.2, 406.1), sent tap down)
I/flutter (18652): ════════════════════════════════════════════════════════════════════════════════════════════════════
W/ActivityThread(18652): handleWindowVisibility: no activity for token android.os.BinderProxy@59b4e8d
I/ViewRootImpl(18652): CPU Rendering VSync enable = true

6 个答案:

答案 0 :(得分:3)

这是因为您要传递给showDialog方法的上下文是context,而在窗口小部件树MaterialLocalizations中还没有MaterialLocalizations小部件MaterialApp小部件会隐式添加该小部件。

要修复此问题,请尝试以下操作:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: "Test",
      home: TestPage(),
    );
  }
}

class TestPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Test")),
      body: Container(
        child: Center(
          child: RaisedButton(
            color: Colors.redAccent,
            textColor: Colors.white,
            onPressed: () {
              testAlert(context);
            },
            child: Text("PressMe"),
          ),
        ),
      ),
    );
  }

  void testAlert(BuildContext context) {
    var alert = AlertDialog(
      title: Text("Test"),
      content: Text("Done..!"),
    );

    showDialog(
        context: context,
        builder: (BuildContext context) {
          return alert;
        });
  }
}

答案 1 :(得分:2)

当您切换到MaterialApp代表不支持的语言时,也会发生这种情况。要理解这是一个棘手的消息,因为它说您应该在树的顶部放置cy-GB,但这可能已经存在。

就我而言,我本地化的语言(英国威尔士语-MaterialApp( localizationsDelegates: [ GlobalMaterialLocalizations.delegate, GlobalWidgetsLocalizations.delegate, GlobalCupertinoLocalizations.delegate, ], supportedLocales: [ const Locale('en', ''), // English, no country code const Locale('he', ''), // Hebrew, no country code const Locale.fromSubtags(languageCode: 'zh') ], // ... ) )无法自动满足。我必须为样板字符串编写自己的委托,并将其添加到应用程序根目录的本地化列表中。

白俄罗斯代表的代码为this。我对其进行了调整,以适应威尔士语。它包含日期格式信息以及材料设计认为您可能需要的大约70个常用短语,例如“全选”,“ 的第页”等。

如果您需要创建一个涵盖全球材料本地化版本中未列出的语言的委托,那么一旦创建了委托,请在代码库中查找,然后在树顶附近的某处显示如下内容:

CyMaterialLocalizations.delegate

只需将localizationsDelegates(或任何您称为新语言的代表)添加到{{1}}列表中。

答案 2 :(得分:0)

对我而言,一个简单的解决方法就是将MaterialApp小部件移至main()方法。

main() {
  runApp(MaterialApp(home: App()));
}

答案 3 :(得分:0)

构建方法应返回 MaterialApp,而不返回脚手架。 在Material App的家中,您可以安装脚手架

from typing import Collection

def fn(arg: Collection[int]):
    pass

答案 4 :(得分:0)

我在showTimePicker内的RaisedButton有相同的问题,

我改组为:

runApp 
  |__MaterialApp
    |__ StatefulWidget/StatelessWidget
      |__SafeArea
        |__Scaffold
          |__ RaisedButton
            |__ showTimePicker

这是示例解决方案:

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

void main() {
  runApp(
    MaterialApp(
      debugShowCheckedModeBanner: false,
      localizationsDelegates: [
        GlobalMaterialLocalizations.delegate,
        GlobalWidgetsLocalizations.delegate,
        GlobalCupertinoLocalizations.delegate,
      ],
      supportedLocales: [
        const Locale('en', 'US'), 
      ],
      home: Sample(),
    ),
  );
}

class Sample extends StatefulWidget {
  @override
  _SampleState createState() => _SampleState();
}

class _SampleState extends State<Sample> {
  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Center(
          child: RaisedButton(
            child: Text('Time Picker'),
            onPressed: () {
              showTimePicker(
                context: context,
                initialTime: TimeOfDay(hour: 10, minute: 47),
                builder: (BuildContext context, Widget child) {
                  return MediaQuery(
                    data: MediaQuery.of(context)
                        .copyWith(alwaysUse24HourFormat: true),
                    child: child,
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}

答案 5 :(得分:0)

另一种方法是用 showDialog 包装调用 Builder 的最内部小部件。在这种情况下,最内部的小部件是 TextButton(请注意,我用 RaisedButton 替换了已弃用的 TextButton)。

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: Text("Test")),
        body: Container(
          child: Builder(
            builder: (context) {
              return TextButton(
                child: const Text('Show'),
                onPressed: () {
                  showDialog(
                    context: context,
                    builder: (_) => AlertDialog(
                      title: Text("Test"),
                      content: Text("Done..!"),
                    ),
                  );
                },
              );
            },
          ),
        ),
      ),
    );
  }
}