我的应用程序的每个“页面”都有一个类,它们都共享相同的appbar,这是它自己的一个类。我在appbar上有一个按钮,我想让它从打开的任何页面调用一个函数。该功能在每个页面上,每页上都有相同的名称。
在下面的缩短代码中,您会看到共享的MyAppBar
,您会看到2页。每个页面都使用MyAppBar
,每个页面都有_myFunction()
。
如何从_myFunction()
的每个当前页面调用MyAppBar
?
class MyAppBar {
setAppBar(context, String title) {
return new AppBar(
backgroundColor: Colors.blue,
title: Text(
title,
style: TextStyle(color: Colors.white),
),
actions: <Widget>[
child: IconButton(myIcon),
onPressed: () => { this should call the current pages _myFunction},),
],
}
}
class _Page1State extends State<Page1>
{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar().setAppBar(context, 'Page 1'),
body: Container(some content here)
)
}
_myFunction()
{
do some stuff;
}
}
class _Page2State extends State<Page2>
{
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar().setAppBar(context, 'Page 2'),
body: Container(some content here)
)
}
_myFunction()
{
do some stuff;
}
}
你可以通过这些功能。
import 'package:flutter/material.dart';
class MyAppBar extends StatelessWidget implements PreferredSizeWidget {
MyAppBar({this.pageInstanceFunction});
var pageInstanceFunction;
@override
Widget build(BuildContext context) {
return AppBar(
backgroundColor: Colors.orange,
title: Text('My Custom AppBar for #page'),
actions: <Widget>[
IconButton(
icon: Icon(Icons.ac_unit),
onPressed: () {
pageInstanceFunction();
},
),
],
);
}
@override
Size get preferredSize => Size.fromHeight(kToolbarHeight);
}
这是我的Page One
import 'package:flutter/material.dart';
import 'package:stackoverflow/MyAppBar.dart';
import 'package:stackoverflow/PageTwo.dart';
class PageOne extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(
pageInstanceFunction: sayHello,
),
body: Container(
color: Colors.deepOrange,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Center(
child: RaisedButton(
onPressed: () {
Navigator.push(
context, MaterialPageRoute(builder: (context) => PageTwo()));
},
child: Text('Page Two'),
),
),
),
);
}
void sayHello() {
print('Hello from PageOne');
}
}
和第二页
import 'package:flutter/material.dart';
import 'package:stackoverflow/MyAppBar.dart';
class PageTwo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: MyAppBar(
pageInstanceFunction: sayHello,
),
body: Container(
color: Colors.lightBlueAccent,
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: Text('Page Two'),
),
);
}
void sayHello() {
print('Hello from PageTwo');
}
}