问题是我要在使用自定义appBar的应用程序抽屉中添加一个应用程序抽屉,这是一个不同的类,我想从没有脚手架的CustomAppBar类中调用应用程序抽屉(添加支架时显示为白屏。
我尝试了多种方法,可以使用IconButton的onPressed属性来调用它。
这是我的主班
class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Container(
child: ListView(
children: <Widget>[
FirstHalf(),
SizedBox(
height: 45.0,
),
for (var foodItem in fooditemList.foodItems)
ItemContainer(foodItem: foodItem)
],
),
),
),
);
}
}
这是CustomAppBar的调用位置
class FirstHalf extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.fromLTRB(35, 25, 0, 0),
child: Column(
children: <Widget>[
CustomAppBar(), //CustomAppBar
SizedBox(
height: 30.0,
),
title(),
SizedBox(
height: 30.0,
),
searchBar(),
SizedBox(
height: 30.0,
),
categories(),
],
),
);
}
此类的代码并未在这里结束,但我认为足够共享而不是共享整个代码
这是CustomAppBar类,我要在其中调用应用抽屉
class CustomAppBar extends StatelessWidget {
final CartListBLoc bloc = BlocProvider.getBloc<CartListBLoc>();
CustomAppBar();
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.only(bottom: 15.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: <Widget>[
IconButton(
icon: Icon(Icons.menu),
onPressed: () {},//want to call app drawer here
),
StreamBuilder(
stream: bloc.listStream,
builder: (context, snapshot) {
List<FoodItem> foodItems = snapshot.data;
int length = foodItems != null ? foodItems.length : 0;
return buildGestureDetector(length, context, foodItems);
},
initialData: <FoodItem>[],
),
],
),
);
}
}
答案 0 :(得分:0)
我可以考虑一种方法,可以将GlobalKey
与ScaffoldState
结合使用。 openDrawer()
上有一种方法ScaffoldState
。
@override
Widget build(BuildContext context) {
final scaffoldKey = GlobalKey<ScaffoldState>(); // Define key
return Scaffold(
key: scaffoldKey, // pass scaffoldKey to Scaffold
drawer: Drawer(), // your drawer implementation
body: SafeArea(
....
FirstHalf(scaffoldKey: scaffoldKey), // Pass scaffold key down the path.
...
....
}
class FirstHalf extends StatelessWidget {
final GlobalKey<ScaffoldState> scaffoldKey;
FirstHalf(this.scaffoldKey);
@override
Widget build(BuildContext context) {
....
....
CustomAppBar(scaffoldKey), //CustomAppBar
....
}
class CustomAppBar extends StatelessWidget {
final GlobalKey<ScaffoldState> scaffoldKey;
final CartListBLoc bloc = BlocProvider.getBloc<CartListBLoc>();
CustomAppBar(this.scaffoldKey);
@override
Widget build(BuildContext context) {
....
....
onPressed: () {
this.scaffoldKey.currentState.openDrawer() // This opens drawer.
},
....
}
通常,我通常会尽量避免使用CustomAppBar。
希望这会有所帮助。