在Flutter中,如果你想要在单击每个按钮时更改AppBar,你可以使用StatefulWidget
来管理AppBar的状态。以下是一个简单的示例,展示了如何实现这一功能:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
AppBar appBar;
@override
void initState() {
super.initState();
appBar = AppBar(
title: Text('Initial Title'),
);
}
void changeAppBarTitle(String newTitle) {
setState(() {
appBar = AppBar(
title: Text(newTitle),
);
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: appBar,
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(
onPressed: () => changeAppBarTitle('Button 1 Clicked'),
child: Text('Button 1'),
),
ElevatedButton(
onPressed: () => changeAppBarTitle('Button 2 Clicked'),
child: Text('Button 2'),
),
],
),
),
);
}
}
build
方法来更新UI。StatefulWidget
可以更好地管理Widget的状态,使得代码更加清晰和易于维护。setState
方法,否则Flutter不会知道状态发生了变化。通过这种方式,你可以轻松地在Flutter中实现单击按钮更改AppBar的功能。
领取专属 10元无门槛券
手把手带您无忧上云