首页 > 解决方案 > 如何将应用栏添加到 StatelessWidget?

问题描述

当我尝试添加此应用栏时,它给了我一个错误。错误是:断言失败:第 4345 行 pos 14:'owner._debugCurrentBuildTarget == this':不正确。

appBar: new AppBar(
  title: new Text("Appbar"),
  actions: <Widget>[
    Padding(
      padding: const EdgeInsets.only(right: 20.0),
      child: Icon(Icons.search),
    ),
  ],
  backgroundColor: Colors.grey,
),

如何将上述应用栏添加到以下代码中?

class StatisticsPage extends StatelessWidget{
  @override
  Widget build(BuildContext context){
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: "Welcome to Flutter",
      home: Statistics(),
    );
  }
}
class Statistics extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Material(
      child:new Container(
        padding: const EdgeInsets.all(30.0),
        color: Colors.white,     
 ...

标签: androidandroid-studioflutter

解决方案


appBar属性位于Scaffold()小部件中。您正在尝试调用appBar不起作用的构建。

class Statistics extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Material(
        child: Scaffold(
      appBar: AppBar(
        title: Text("Appbar"),
        actions: <Widget>[
          Padding(
            padding: const EdgeInsets.only(right: 20.0),
            child: Icon(Icons.search),
          ),
        ],
        backgroundColor: Colors.grey,
      ),
      body: Container(
        padding: const EdgeInsets.all(30.0),
        color: Colors.white,
      ),
    ));
  }
}

您似乎对 Flutter 很陌生,或者您只是从某个旧存储库中复制粘贴代码。

new自 Dart 2.0 起,不再需要应用该关键字。先学 Dart,再学 Flutter,可以从 Youtube 教程开始。


推荐阅读