Как создать собственный виджет AppBar?

Я новичок в флаттере. Я пытаюсь создать собственный виджет панели приложений и импортировать виджет на страницы.

Но мне не удалось создать виджет.

import 'package:flutter/material.dart';
 
 class AppBar extends StatelessWidget{
  @override
  Widget build(BuildContext context){
return AppBar(
  title: Text('Ordering'),
  actions: <Widget>[
    IconButton(
      onPressed: _incrementCounter,
      icon: Icon(Icons.add),
    ),
    BadgeIconButton(
      itemCount: _counter,
      badgeColor: Color.fromRGBO(37, 134, 16, 1.0),
      badgeTextColor: Colors.white,
      icon: Icon(Icons.shopping_cart, size: 30.0,),
      onPressed: () {}
    ),
  ],
);

} }'


person KURRU HEM    schedule 14.11.2018    source источник


Ответы (7)


import 'package:flutter/material.dart';

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {
    CustomAppBar({Key key}) : preferredSize = Size.fromHeight(kToolbarHeight), super(key: key);

    @override
    final Size preferredSize; // default is 56.0

    @override
    _CustomAppBarState createState() => _CustomAppBarState();
}

class _CustomAppBarState extends State<CustomAppBar>{

    @override
    Widget build(BuildContext context) {
        return AppBar( title: Text("Sample App Bar") );
    }
}

Надеюсь, это поможет

person riftninja    schedule 24.01.2019
comment
Кроме того, в material.dart есть константа kToolbarHeight, поэтому лучше использовать preferredSize = Size.fromHeight(kToolbarHeight) - person no_fate; 28.06.2019
comment
Спасибо! Этот подход работает, если вы хотите, чтобы ваш CustomAppBar был в отдельном файле (что рекомендуется). - person Kirill Karmazin; 26.11.2019
comment
Это должен быть принятый ответ. Я бы добавил, что здесь нет необходимости создавать StatefulWidget. Вы можете сделать его StatelessWidget. Вы также можете установить атрибут selectedSize напрямую, как final Size preferredSize = Size.fromHeight(kToolbarHeight), чтобы упростить конструктор. - person Venkat D.; 09.04.2021

Я расширил AppBar своим собственным виджетом. Затем передал мои параметры в суперкласс.

class CustomAppBar extends AppBar {
  CustomAppBar()
      : super(
          title: Text('MyApp'),
          actions: [
            IconButton(icon: Icon(Icons.search), onPressed: () {}),
          ],
        );
}
person Saud Bako    schedule 07.10.2020

Отредактируйте ответ riftninja:

import 'package:flutter/material.dart';

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {
  CustomAppBar({Key key, double height}) : preferredSize = 
       Size.fromHeight(height), super(key: key);

  @override
  //final Size preferredSize; // This didnot work for me.
  Size get preferredSize => preferredSize; //This should work.

  @override
  _CustomAppBarState createState() => _CustomAppBarState();
  }

 class _CustomAppBarState extends State<CustomAppBar>{

  @override
  Widget build(BuildContext context) {
    return AppBar( title: Text("Sample App Bar") );
  }
  }

Это также работает для виджета без сохранения состояния.

person Bensal    schedule 21.08.2020

AppBar реализует класс PreferredSizeWidget, что означает, что AppBar должен иметь предпочтительный размер.

Переменная preferredSize переопределена, поскольку она реализована из PreferredSizeWidget, здесь вы можете установить высоту вашего желания.

class CustomAppBar extends StatefulWidget implements PreferredSizeWidget {
  CustomAppBar({Key key}) : preferredSize = Size.fromHeight(60.0), super(key: key);

  @override
  final Size preferredSize;

  @override
  _CustomAppBarState createState() => _CustomAppBarState();
}

class _CustomAppBarState extends State<CustomAppBar>{

  @override
  Widget build(BuildContext context) {
    return AppBar(
      title: Text('App Bar'),
      actions: <Widget>[
        IconButton(
          icon: Icon(Icons.add, color: Colors.white,),
        ),
      ],
    );
  }
}

И использовать так

class _MyHomePageState extends State<MyHomePage> {
  
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: CustomAppBar()
    );
  }

введите здесь описание изображения

person Paresh Mangukiya    schedule 14.09.2020

widget_appbar.dart

class WidgetAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Color? backgroundColor;
  final Color? textIconColor;
  final String? icon;
  final String? title;
  final double? height;
  final List<Widget>? menuItem;
  final bool hideBack;

  WidgetAppBar({
    this.backgroundColor = whiteColor,
    this.textIconColor = headingColor,
    this.icon,
    this.title = '',
    this.menuItem,
    this.height: kToolbarHeight,
    this.hideBack = false,
  });

  @override
  Size get preferredSize => Size.fromHeight(height!);

  @override
  Widget build(BuildContext context) {
    return AppBar(
      actions: menuItem,
      toolbarHeight: preferredSize.height,
      iconTheme: IconThemeData(
        color: textIconColor,
      ),
      leading: hideBack
          ? Container()
          : icon == null
              ? BackButton()
              : IconButton(
                  icon: Image.asset(
                    icon!,
                    height: 18,
                    width: 18,
                  ),
                  onPressed: () {
                    Navigator.pop(context, true);
                  },
                ),
      title: Text(
        title!,
        style: TextStyle(
          fontSize: 20,
          fontWeight: FontWeight.bold,
          color: textIconColor,
        ),
      ),
      backgroundColor: backgroundColor,
      centerTitle: true,
    );
  }
}

Как использовать?

@override
Widget build(BuildContext context) {
  return Scaffold(
    appBar: WidgetAppBar(
      icon: ic_back_black,
      title: 'Toolbar Title',
    ),
    body: SafeArea(
      child: Container(),
    ),
  );
}
person Ketan Ramani    schedule 16.07.2021

Screenshot (Null Safe):

введите здесь описание изображения


Full code:

Создайте этот класс.

class CustomAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Widget child;
  final double height;

  CustomAppBar({
    required this.child,
    this.height = kToolbarHeight,
  });

  @override
  Size get preferredSize => Size.fromHeight(height);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: preferredSize.height,
      color: Colors.red,
      child: child,
    );
  }
}

Использование:

Scaffold(
  appBar: CustomAppBar(
    height: 100,
    child: Column(
      children: [
        FlutterLogo(size: 56),
        SizedBox(height: 8),
        Text('Flutter'),
      ],
    ),
  ),
)
person CopsOnRoad    schedule 22.07.2021

person    schedule
comment
Я пытаюсь создать виджет панели приложений в отдельном файле дротика и импортировать. - person KURRU HEM; 14.11.2018
comment
Вы можете создать виджет с помощью функции setAppBar. Затем добавьте его в свой основной интерфейс. - person Rafiqul Hasan; 14.11.2018
comment
Спасибо за вашу поддержку, но ваш ответ работает, только если виджет панели приложений создан в том же файле. - person KURRU HEM; 14.11.2018
comment
Следуйте этой инструкции, как создать собственный виджет, и используйте этот код для создания собственной панели приложений. youtube.com/watch?v=W1pNjxmNHNQ - person Rafiqul Hasan; 14.11.2018
comment
Тип аргумента «AppBarWidget» не может быть назначен типу параметра «PreferredSizeWidget». Получение вышеуказанной ошибки - person KURRU HEM; 14.11.2018