【发布时间】:2021-03-01 20:45:41
【问题描述】:
假设我在 Material App 中有一个基本页面。 基本页面只有一个小部件,一个脚手架。 脚手架包含一个应用栏,即在每个页面中通过应用保持不变。 脚手架还包含一个主体,它应该被扩展基础的页面覆盖以显示其内容。
我该怎么做呢? 感谢您的帮助!
【问题讨论】:
假设我在 Material App 中有一个基本页面。 基本页面只有一个小部件,一个脚手架。 脚手架包含一个应用栏,即在每个页面中通过应用保持不变。 脚手架还包含一个主体,它应该被扩展基础的页面覆盖以显示其内容。
我该怎么做呢? 感谢您的帮助!
【问题讨论】:
一种方法是在 StatefulWidget 中创建一个保存当前路由的变量。
Widget currentBody = your initial body ;
然后在您想使用 setState 切换主体时更改该变量:
SetState(() { currentBody = your new body widget }) ;
在您放置的 appbar 之后的脚手架中!
body : currentBody ;
【讨论】:
你有很多方法可以做到这一点,一种是使用Bloc package,但另一种方法是使用底部导航栏](https://api.flutter.dev/flutter/material/BottomNavigationBar-class.html)
底部导航栏由多个项目组成,这些项目以文本标签、图标或两者的形式,布置在一块材料的顶部。它在应用程序的顶级视图之间提供快速导航。对于更大的屏幕,侧边导航可能更适合。
底部导航栏通常与 Scaffold 结合使用,它作为 Scaffold.bottomNavigationBar 参数提供。
我在transparent appbar的回答中提供了一个例子,当然你不需要你的appbar是透明的。
class HomePageState extends State<Homepage> {
List<Widget> widgets = [Text("haha"), Placeholder(), Text("hoho")]; // as many widgets as you have buttons.
Widget currentWidget = widgets[0];
void _onItemTapped(int index) {
setState(() {
NavigationBar._selectedIndex = index;
currentWidget = widgets[index];
});
}
@override
Widget build(BuildContext context) {
return return MaterialApp(
home: Scaffold(
extendBody: true, // very important as noted
bottomNavigationBar: BottomNavigationBar(
currentIndex: NavigationBar._selectedIndex,
selectedItemColor: Colors.amber[800],
onTap: _onItemTapped,
backgroundColor: Color(0x00ffffff), // transparent
type: BottomNavigationBarType.fixed,
unselectedItemColor: Colors.blue,
items: const <BottomNavigationBarItem>[
BottomNavigationBarItem(
icon: Icon(Icons.home),
title: Text('Home'),
),
BottomNavigationBarItem(
icon: Icon(Icons.grade),
title: Text('Level'),
),
[...] // remaining in the link
),
body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: ExactAssetImage("assets/background.png"), // because if you want a transparent navigation bar I assume that you have either a background image or a background color.
fit: BoxFit.fill
),
),
child: currentWidget
),
),
);
}
}
...
Bloc 架构更难理解,您需要阅读文档并尝试教程,但实现起来也很有趣。
【讨论】:
您可以像这样创建一个全局可访问的页面:
base_page.dart
import 'package:flutter/material.dart';
class BasePage extends StatelessWidget {
/// Body of [BasePage]
final Widget body;
const BasePage({@required this.body, Key key})
: assert(body != null),
super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
// Your appbar content here
),
body: body,
);
}
}
当您想使用它时,只需将body 提供给新类,如下所示:
main.dart
import 'package:flutter/material.dart';
import 'base_page.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return BasePage(
// This is where you give you custom widget it's data.
body: Center(child: Text('Hello, World')),
);
}
}
【讨论】: