找不到任何材料小部件

159

我是Flutter的新手,我正在尝试执行这里的示例。我只想使用TextField小部件来获取一些用户输入。问题在于我收到了“找不到Material widget”的错误提示。我做错了什么?谢谢。

代码:

import 'package:flutter/material.dart';    

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


class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      home: new ExampleWidget(),
    );
  }
}


/// Opens an [AlertDialog] showing what the user typed.
class ExampleWidget extends StatefulWidget {
  ExampleWidget({Key key}) : super(key: key);

  @override
  _ExampleWidgetState createState() => new _ExampleWidgetState();
}

/// State for [ExampleWidget] widgets.
class _ExampleWidgetState extends State<ExampleWidget> {
  final TextEditingController _controller = new TextEditingController();

  @override
  Widget build(BuildContext context) {
    return new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        new TextField(
          controller: _controller,
          decoration: new InputDecoration(
            hintText: 'Type something',
          ),
        ),
        new RaisedButton(
          onPressed: () {
            showDialog(
              context: context,
              child: new AlertDialog(
                title: new Text('What you typed'),
                content: new Text(_controller.text),
              ),
            );
          },
          child: new Text('DONE'),
        ),
      ],
    );
  }
}

这是错误堆栈:

Launching lib/main.dart on Android SDK built for x86 in debug mode...
Built build/app/outputs/apk/app-debug.apk (21.5MB).
I/flutter ( 5187): ══╡ EXCEPTION CAUGHT BY WIDGETS LIBRARY ╞═══════════════════════════════════════════════════════════
I/flutter ( 5187): The following assertion was thrown building InputDecorator(decoration: InputDecoration(hintText:
I/flutter ( 5187): "Type something"); baseStyle: null; isFocused: false; isEmpty: true; dirty):
I/flutter ( 5187): No Material widget found.
I/flutter ( 5187): InputDecorator widgets require a Material widget ancestor.
I/flutter ( 5187): In material design, most widgets are conceptually "printed" on a sheet of material. In Flutter's
I/flutter ( 5187): material library, that material is represented by the Material widget. It is the Material widget
I/flutter ( 5187): that renders ink splashes, for instance. Because of this, many material library widgets require that
I/flutter ( 5187): there be a Material widget in the tree above them.
I/flutter ( 5187): To introduce a Material widget, you can either directly include one, or use a widget that contains
I/flutter ( 5187): Material itself, such as a Card, Dialog, Drawer, or Scaffold.
I/flutter ( 5187): The specific widget that could not find a Material ancestor was:
I/flutter ( 5187):   InputDecorator(decoration: InputDecoration(hintText: "Type something"); baseStyle: null;
I/flutter ( 5187):   isFocused: false; isEmpty: true)
I/flutter ( 5187): The ownership chain for the affected widget is:
I/flutter ( 5187):   InputDecorator ← AnimatedBuilder ← Listener ← _GestureSemantics ← RawGestureDetector ←
I/flutter ( 5187):   GestureDetector ← TextField ← Column ← ExampleWidget ← _ModalScopeStatus ← ⋯
I/flutter ( 5187): 
I/flutter ( 5187): When the exception was thrown, this was the stack:
I/flutter ( 5187): #0      debugCheckHasMaterial.<anonymous closure> (package:flutter/src/material/debug.dart:26)
I/flutter ( 5187): #2      debugCheckHasMaterial (package:flutter/src/material/debug.dart:23)
I/flutter ( 5187): #3      InputDecorator.build (package:flutter/src/material/input_decorator.dart:334)
... <output omitted>
I/flutter ( 5187): (elided one frame from class _AssertionError)
I/flutter ( 5187): ════════════════════════════════════════════════════════════════════════════════════════════════════
I/flutter ( 5187): Another exception was thrown: No Material widget found.
11个回答

223
错误信息显示:

要引入一个Material小部件,您可以直接包含一个, 或使用一个包含Material本身的小部件,如Card, Dialog, DrawerScaffold

在您的情况下,我可能会将您的Column包装在Scaffold中。这将使您稍后可以轻松添加其他材料小部件到您的应用程序中,例如AppBarDrawerFloatingActionButton
@override
Widget build(BuildContext context) {
  return new Scaffold(
    body: new Column(
      mainAxisAlignment: MainAxisAlignment.center,
      children: <Widget>[
        new TextField(
            controller: _controller,
            decoration: new InputDecoration(
                hintText: 'Type something',
            ),
        ),
        new RaisedButton(
            onPressed: () {
              showDialog(
                  context: context,
                  child: new AlertDialog(
                      title: new Text('What you typed'),
                      content: new Text(_controller.text),
                  ),
              );
            },
            child: new Text('DONE'),
        ),
      ],
    ),
  );
}

这种方法的挑战在于新页面既不包含底部导航栏,也不包含应用程序的主题,我们能否在同一个应用程序中拥有两个MaterialApps? - utkarshk

33

只需使用Material widget包装您的小部件,问题就会得到解决。

Material(
  child: InkWell(
    onTap: onPressed,));

4
这是一个更好的修复方案。 - Fethi

17

在我的情况下,我正在使用一个英雄小部件(hero widget)在一个像这样的脚手架(scaffold)中。

Scaffold(
  body:Hero(
    child:ListView(
      children:<Widget>[
        TextField(),
           ...
           ...
      ]
    )
  )
);

我只是将 Hero Widget 移出 Scaffold,问题就解决了。

Hero(
  child:Scaffold(
    body:ListView(
      children:<Widget>[
        TextField(),
        ...
        ...
      ]
    )
  )
);

6
将您的小部件放在Scaffold中,就像这样:
    import 'package:flutter/material.dart';

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

    class MyApp extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return MaterialApp(
          title: 'Demo',
          //home: MyWidget(), --> do not do this !!!
          home: Home() --> this will wrap it in Scaffold
        );
      }
    }

    class Home extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Scaffold(
            appBar: AppBar(
              title: Text('Demo'),
            ),
            body: MyWidget()); --> put your widget here
      }
    }

class MyWidget extends StatefulWidget {
...

4

使用 GestureDetector 组件代替 InkWell,对我而言可以解决问题。


3
错误的意思是您需要在Material小部件内包装该列,您可以将其放置在脚手架的正文中或将其放置为Materialapp的主页。例如:
 return MaterialApp(
   home: Column(
     mainAxisAlignment: MainAxisAlignment.center,
     children: [
       TextField(
         controller: _controller,
         decoration: new InputDecoration(hintText: 'Type something'),
       ),
     ]
   ),
 );

或者

return MaterialApp(
   body: Column(
     mainAxisAlignment: MainAxisAlignment.center,
     children: [
       TextField(
         controller: _controller,
         decoration: new InputDecoration(hintText: 'Type something'),
       ),
     ]
   ),
 );

1

这可能是由于错误的路由引起的。

逐一检查您的路由。 enter image description here


1
将您的 Column 用 Scaffold 或 Material 包装起来。

1

在使用hero动画小部件时,我采用了以下方法。

    @override
  Widget build(BuildContext context) {
    bool isKeyboardShowing = MediaQuery.of(context).viewInsets.vertical > 0;
    return Scaffold(
        resizeToAvoidBottomInset: false,
        body: Hero(
          tag: AppStrings.imageSignIn,
          child: Material(
            child: Container()),

个人建议:不要在脚手架上方使用Hero widget,因为它会留在widget树中,当屏幕上显示任何snackbar时会抛出异常。谢谢。

0
尝试这种方法:只需将builder行添加到MaterialApp中即可:
builder: (context, child) => Material(child: child),

在这里,您还可以提供一个典型的页面,其中包括AppBarBodyScrollConfigurationPlatform和其他元素,您可以根据需要添加全局监听器。这非常方便 :) 并且沿路的任何页面都将被包装。

例如,从传递给此方法的BuildContext中,Directionality、Localizations、DefaultTextStyle、MediaQuery等都是可用的。它们也可以以影响Navigator或Router中所有路由的方式进行覆盖。

这很少有用,但可以在希望覆盖这些默认值的应用程序中使用,例如,尽管使用英语,但强制将应用程序置于从右到左模式,或者覆盖MediaQuery指标(例如,为OEM代码显示的插件留出广告间隙)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接