BottomNavigationBar с элементами меню, поиска и переполнения
BottomNavigationBar используется для размещения меню действий в нижней части приложения Flutter. Этот виджет полезен для размещения меню действий, предназначенных для текущей страницы. Этот рецепт покажет, как реализовать нижнюю панель навигации с меню, чтобы открыть ящик для дополнительных элементов действий, таких как «добавить» и «редактировать», действие меню «поиск» и, наконец, элемент действия меню переполнения.
Целевая аудитория: Новичок
Рецепт: Реализуйте BottomNavigationBar с помощью BottomAppBar с элементами меню, поиска и действия переполнения.
Виджет фокуса: Нижняя панель приложений
Цель: BottomNavigationBar отображает меню для вызова нижнего навигационного ящика, фиктивный значок действия поиска и меню элементов действий переполнения. Щелчок по каждому действию меню отобразит сообщение с использованием Флаттертост
Проверка в действии здесь
Поехали!
Шаг 1. Поскольку мы будем использовать fluttertoast
для отображения сообщений о состоянии сначала мы добавим fluttertoast
зависимость от библиотеки в pubspec.yaml
как показано ниже:
dependencies:
flutter:
sdk: flutter
#added fluttertoast library to show status messages
fluttertoast: ^2.1.0
Нажмите «Получить/обновить зависимости», когда появится приглашение. Вы можете убедиться, что все зависимости обновлены.
Шаг 2. Добавьте верхнюю часть заполнителя для приложения, используя Center
виджет. я буду использовать Text
виджет для показа демонстрационного сообщения.
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Checkout BottomNavigationBar in action below'),
),
...
);
}
Шаг 3. Добавлять BottomAppBar
виджет с использованием bottomNavigationBar
атрибут.
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomAppBar(
...
);
}
Шаг №4. Добавить дочерний компонент Row
к BottomAppBar
.
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomAppBar(
child: Row(
),
...
);
}
Шаг № 5. Теперь пришло время добавить виджеты действий меню. Виджеты добавляются как children
к Row
составная часть.
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
...
],
),
...
);
}
Шаг №6. Далее я добавлю наш самый первый элемент действия меню в качестве виджета действия первого дочернего меню. я буду использовать IconButton
виджет. При нажатии на это меню действий оно откроется модальный нижний лист.
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
// Bottom that pops up from the bottom of the screen.
IconButton(
icon: Icon(Icons.menu),
onPressed: () {
showModalBottomSheet<Null>(
context: context,
builder: (BuildContext context) => openBottomDrawer(),
);
},
),
],
),
...
);
}
Ящик, открытый в модальном нижнем листе, имеет два действия меню: «Редактировать» и «Добавить». Это выглядит так:
Widget openBottomDrawer() {
return Drawer(
child: Column(
children: const <Widget>[
//Add menu item to edit
const ListTile(
leading: const Icon(Icons.mode_edit),
title: const Text('Edit'),
),
const ListTile(
//Add menu item to add a new item
leading: const Icon(Icons.add),
title: const Text('Add'),
),
],
),
);
}
Шаг №7. Еще два IconButton
добавлены виджеты для пунктов меню «Поиск» и меню переполнения как children
виджеты.
@override
Widget build(BuildContext context) {
return Scaffold(
...
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
//First action menu widget
// Bottom that pops up from the bottom of the screen.
IconButton(
icon: Icon(Icons.menu),
onPressed: () {
showModalBottomSheet<Null>(
context: context,
builder: (BuildContext context) => openBottomDrawer(),
);
},
),
//Second action menu widget for Search
IconButton(
icon: Icon(Icons.search),
onPressed: () {
Fluttertoast.showToast(msg: 'Clicked on Search menu action.');
},
),
//Third action menu widget for overflow action
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {
Fluttertoast.showToast(msg: 'This is where overflow menu actions will go');
},
),
],
),
);
}
Полный пример кода
import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BottomNavigationBarRecipe',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: BottomNavigationBarRecipe(title: 'Flutter Demo Home Page'),
);
}
}
class BottomNavigationBarRecipe extends StatefulWidget {
BottomNavigationBarRecipe({Key key, this.title}) : super(key: key);
final String title;
@override
_BottomNavigationBarRecipeState createState() => _BottomNavigationBarRecipeState();
}
class _BottomNavigationBarRecipeState extends State<BottomNavigationBarRecipe> {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text('Checkout BottomNavigationBar in action below'),
),
bottomNavigationBar: BottomAppBar(
child: Row(
children: <Widget>[
// Bottom that pops up from the bottom of the screen.
IconButton(
icon: Icon(Icons.menu),
onPressed: () {
showModalBottomSheet<Null>(
context: context,
builder: (BuildContext context) => openBottomDrawer(),
);
},
),
IconButton(
icon: Icon(Icons.search),
onPressed: () {
Fluttertoast.showToast(msg: 'Clicked on Search menu action.');
},
),
IconButton(
icon: const Icon(Icons.more_vert),
onPressed: () {
Fluttertoast.showToast(msg: 'This is where overflow menu actions will go');
},
),
],
)),
);
}
//This drawer is opened in modal bottom sheet
Widget openBottomDrawer() {
return Drawer(
child: Column(
children: const <Widget>[
//Add menu item to edit
const ListTile(
leading: const Icon(Icons.mode_edit),
title: const Text('Edit'),
),
const ListTile(
//Add menu item to add a new item
leading: const Icon(Icons.add),
title: const Text('Add'),
),
],
),
);
}
}
Репозиторий исходного кода: Исходный код рецепта доступен здесь
Использованная литература:
Понравилась статья? Пожалуйста, дайте мне знать в комментариях ниже, какие еще темы вы хотели бы, чтобы я написал.