我正在flutter中创建我自己的样式按钮。到目前为止,我创建了一个commonui.dart文件,并放置了以下代码
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
CustomButton({@required this.onPressed});
final GestureTapCallback onPressed;
@override
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
SizedBox(
width: 10.0,
),
Text(
"Tap Me",
maxLines: 1,
style: TextStyle(color: Colors.white,fontFamily: 'ActoBold'),
),
],
),
),
onPressed: onPressed,
);
}
}从我的页面调用它,就像这样
CustomButton(
onPressed: () {
print("Tapped Me");
},
)我想让按钮文本动态化。如何将变量传递给CustomButton小部件?
发布于 2020-04-30 13:51:55
就像您刚才对onPressed函数所做的那样。唯一的区别是类型将是字符串。
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
class CustomButton extends StatelessWidget {
final GestureTapCallback onPressed;
final String buttonText;
CustomButton({@required this.onPressed, this.buttonText});
@override
Widget build(BuildContext context) {
return RawMaterialButton(
fillColor: Colors.green,
splashColor: Colors.greenAccent,
child: Padding(
padding: EdgeInsets.all(10.0),
child: Row(
mainAxisSize: MainAxisSize.min,
children: const <Widget>[
SizedBox(
width: 10.0,
),
Text(
buttonText ?? 'Tap me',
maxLines: 1,
style: TextStyle(color: Colors.white,fontFamily: 'ActoBold'),
),
],
),
),
onPressed: onPressed,
);
}
}然后,您可以将值传递给CustomButton。
CustomButton(
buttonText: 'Updated Text',
onPressed: () {
print("Tapped Me");
},
)如果要在单击按钮时动态更改该值,请使用有状态小部件:
class App extends StatefulWidget {
@override
_AppState createState() => _AppState();
}
class _AppState extends State<App> {
String _buttonText;
Widget build(BuildContext context) {
return Scaffold(
body: CustomButton(
buttonText: _buttonText,
onPressed: () {
print("Tap Me");
setState(() {
_buttonText = 'Tapped';
});
},
),
);
}
}发布于 2020-04-30 12:58:11
执行以下更改...
CustomButton(
child: Text(trigger),
onPressed: () {
setState((){
trigger="tapped me";
})
},
)不要忘记声明变量,并将您的类无状态更改为有状态小部件。
https://stackoverflow.com/questions/61516094
复制相似问题