为什么我不能把Material AppBar做成一个独立的类?

问题描述 投票:0回答:1

我想把我的应用条的代码在我的 Scaffold 小部件到一个单独的类中。

我写了这个(编译后不能正确显示)。

    class MyAppBar extends AppBar {
  Widget build(BuildContext context) {
    return AppBar(
      title: const Text('Sample Code'),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          tooltip: 'Navigation menu',
          onPressed: null,
        ),
        IconButton(
          icon: Icon(Icons.search),
          tooltip: 'Search',
          onPressed: null,
        ),
      ],
    );
  }
}

class MyScaffold extends StatefulWidget {
  _MyScaffoldState createState() => _MyScaffoldState();
}

class _MyScaffoldState extends State<MyScaffold> {
  bool pressed = false;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MyAppBar(),

它显示的是:enter image description here

当这段代码编译后,正确地显示出AppBar,

class MyScaffold extends StatefulWidget {
  _MyScaffoldState createState() => _MyScaffoldState();
}

class _MyScaffoldState extends State<MyScaffold> {
  bool pressed = false;

  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Sample Code'),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.menu),
            tooltip: 'Navigation menu',
            onPressed: null,
          ),
          IconButton(
            icon: Icon(Icons.search),
            tooltip: 'Search',
            onPressed: null,
          ),
        ],
      ),

它看起来是这样的enter image description here

有谁能帮我解决这个问题吗?

flutter flutter-layout
1个回答
1
投票

答案在这里。单独处理应用栏

我需要 class MyAppBar extends StatelessWidget 将要 class MyAppBar extends StatelessWidget implements PreferredSizeWidget


-1
投票

试着用这个类代替你的MyAppBar类。

class MyAppBar extends StatefulWidget {
  _MyAppBarState createState() => _MyAppBarState();
}

class _MyAppBarState extends State<MyAppBar> {

  Widget build(BuildContext context) {
    return AppBar(
      title: const Text('Sample Code'),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.menu),
          tooltip: 'Navigation menu',
          onPressed: null, // null disables the button
        ),
        // Expanded expands its child to fill the available space.
        IconButton(
          icon: Icon(Icons.search),
          tooltip: 'Search',
          onPressed: null,
        ),
      ],
    );
  }
}

在制作自己的小部件时,一定要扩展无状态或有状态。

© www.soinside.com 2019 - 2024. All rights reserved.