Общая панель приложений Flutter с настраиваемой кнопкой действия

Я новичок в флаттере, и у меня есть общий appBar, отделенный от main.dart, поэтому я могу использовать его на каждом экране. Вот файл dart с appBar.

import 'package:flutter/material.dart';
import 'package:voota/utils/Hex2Color.dart';
import 'package:intl/intl.dart';

class BaseAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Color bgColor = HexToColor('#508bbb');
  final String title;
  final AppBar appBar;
  final List<Widget> widgets;

  BaseAppBar({Key key, this.title, this.appBar, this.widgets})
     : super(key: key);

  @override
  Widget build(BuildContext context) {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('MMMM d, y').format(now);

    return AppBar(
      title: RichText(
        text: TextSpan(
            text: 'VOOTA ' + title,
            style: TextStyle(
              fontSize: 15.0,
              color: Colors.white,
            ),
            children: [
              TextSpan(text: '\n'),
              TextSpan(
                text: formattedDate,
                style: TextStyle(
                  fontSize: 10.0,
                  color: Colors.white,
                ),
              ),
            ]),
        textAlign: TextAlign.center,
      ),
      centerTitle: true,
      backgroundColor: bgColor,
      elevation: 0,
      //actions: widgets,
    );
  }

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

Я просто импортирую файл dart, в котором определен appBar, и поэтому на каждом экране у меня есть один и тот же appBar, например:

Widget build(BuildContext context) {
return Scaffold(
    appBar: BaseAppBar(title: title, appBar: AppBar()),
    ....

Теперь мне нужна кнопка действия (раскрывающееся меню переполнения) на некоторых экранах. Но действия различаются от экрана к экрану. Как я могу это определить? На одном экране есть только обновление в меню выбора, а на другом экране есть обновление, выход из системы и параметры активации с разными маршрутами. А на панели инструментов вообще нет никаких действий ... Спасибо за любую помощь, совет или ссылку;)


person cwhisperer    schedule 14.11.2019    source источник


Ответы (2)


Я сделал это следующим образом, надеюсь, это правильно: в моем AppBar я добавил класс с DropdownChoices и расширил BaseAppBar параметром dropdownChoices.

import 'package:flutter/material.dart';
import 'package:voota/utils/Hex2Color.dart';
import 'package:intl/intl.dart';

class BaseAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Color bgColor = HexToColor('#508bbb');
  final String title;
  final AppBar appBar;
  final List<Widget> widgets;
  final List<DropdownChoices> dropdownChoices;

  BaseAppBar({Key key, this.title, this.appBar, this.widgets, this.dropdownChoices}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    DateTime now = DateTime.now();
    String formattedDate = DateFormat('MMMM d, y').format(now);

    print('app bar. count dropdown choices ${dropdownChoices.length}');

    return AppBar(
      title: RichText(
        text: TextSpan(
            text: 'VOOTA ' + title,
            style: TextStyle(
              fontSize: 15.0,
              color: Colors.white,
            ),
            children: [
              TextSpan(text: '\n'),
              TextSpan(
                text: formattedDate,
                style: TextStyle(
                  fontSize: 10.0,
                  color: Colors.white,
                ),
              ),
            ]),
        textAlign: TextAlign.center,
      ),
      centerTitle: true,
      backgroundColor: bgColor,
      elevation: 0,
      actions: <Widget>[
        PopupMenuButton<DropdownChoices>(
          onSelected: null,
          elevation: 6,
          itemBuilder: (BuildContext context) {
            return dropdownChoices.map((DropdownChoices choice) {
              return PopupMenuItem<DropdownChoices>(
                value: choice,
                child: Text(choice.title),
              );
            }).toList();
          },
        ),
      ],
    );
  }

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

class DropdownChoices {
  const DropdownChoices({this.title, this.icon});

  final String title;
  final IconData icon;
}

На каждом экране, где мне нужен AppBar, я импортирую файл AppBar.dart и передаю dropdownChoices в AppBar, например:

class UserProfile extends StatefulWidget {
  @override
  _UserProfile createState() => _UserProfile();
}

class _UserProfile extends State<UserProfile> {
  final String title = 'Profile';
  final bgcolor = HexToColor('#508bbb');
  final list = List();
  final isLoading = false;

  List<DropdownChoices> userdropdownchoices = <DropdownChoices>[
    DropdownChoices(title: 'Bike', icon: Icons.directions_bike),
    DropdownChoices(title: 'Car', icon: Icons.directions_car),
    DropdownChoices(title: 'Bus', icon: Icons.directions_bus),
    DropdownChoices(title: 'Trains', icon: Icons.directions_railway),
  ];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: BaseAppBar(title: title, appBar: AppBar(), dropdownChoices: userdropdownchoices),
        .....

Кажется, это работает ... Теперь я должен проверить, содержит ли список элементы и отображать или нет DropDownMenu. Но я открыт для любых предложений;)

person cwhisperer    schedule 29.11.2019

решение 1

Сделайте более одного настраиваемого appBar.

решение 2

Добавить тип строки

class BaseAppBar extends StatelessWidget implements PreferredSizeWidget {
  final Color bgColor = HexToColor('#508bbb');
  final String title;
  final AppBar appBar;
  final List<Widget> widgets;
  final String type;

потом

@override
  Widget build(BuildContext context) {

IconButton iconButton;
    if(widget.type=='add'){
      iconButton =IconButton(icon: Icon(Icons.add),onPressed: (){});
    }else if(widget.type=='delete'){
      iconButton =IconButton(icon: Icon(Icons.delete),onPressed: (){});
    }
return iconButton;
}

Также вы можете использовать enum вместо String https://www.tutorialspoint.com/dart_programming/dart_programming_enumeration.htm

person suhaib salem    schedule 14.11.2019