我已经看到我无法在Flutter中设置RaisedButton
的宽度。如果我已经很好理解,我应该将RaisedButton
放入SizedBox
。然后我将能够设置盒子的宽度或高度。这是对的吗?还有其他办法吗?
在每个按钮周围创建SizedBox
这有点乏味,所以我想知道为什么他们选择这样做。我很确定他们有充分的理由这样做,但我没有看到它。
脚手架很难阅读和为初学者建造。
new SizedBox(
width: 200.0,
height: 100.0,
child: new RaisedButton(
child: new Text('Blabla blablablablablablabla bla bla bla'),
onPressed: _onButtonPressed,
),
),
答案 0 :(得分:34)
如文档here
中所述凸起的按钮的最小尺寸为88.0 x 36.0,可以 被ButtonTheme覆盖。
你可以那样做
ButtonTheme(
minWidth: 200.0,
height: 100.0,
child: RaisedButton(
onPressed: () {},
child: Texts.black("test"),
),
);
答案 1 :(得分:16)
对于match_parent
,您可以使用
SizedBox(
width: double.infinity, // match_parent
child: RaisedButton(...)
)
对于任何特定的值,您都可以使用
SizedBox(
width: 100, // specific value
child: RaisedButton(...)
)
答案 2 :(得分:5)
只需使用Error: Request aborted
at IncomingMessage.<anonymous> (C:\Users\pranav kaushik\Desktop\Network\node_app\public\node_modules\formidable\lib\incoming_form.js:122:19)
at IncomingMessage.emit (events.js:315:20)
at abortIncoming (_http_server.js:537:9)
at socketOnEnd (_http_server.js:553:5)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1201:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
Error: Request aborted
at IncomingMessage.<anonymous> (C:\Users\pranav kaushik\Desktop\Network\node_app\public\node_modules\formidable\lib\incoming_form.js:122:19)
at IncomingMessage.emit (events.js:315:20)
at abortIncoming (_http_server.js:537:9)
at socketOnEnd (_http_server.js:553:5)
at Socket.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1201:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
,其中import UIKit
class ViewController: UIViewController {
private var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
let flowLayout = createCompositionalLayout()
self.collectionView = UICollectionView(frame: .zero, collectionViewLayout: flowLayout)
collectionView.register(HostingCollectionViewCell.self, forCellWithReuseIdentifier: "HostingCollectionViewCell")
collectionView.delegate = self
collectionView.dataSource = self
collectionView.isDirectionalLockEnabled = true
collectionView.isPagingEnabled = true
collectionView.showsVerticalScrollIndicator = false
collectionView.contentInsetAdjustmentBehavior = .never
collectionView.showsHorizontalScrollIndicator = false
collectionView.alwaysBounceHorizontal = false
collectionView.translatesAutoresizingMaskIntoConstraints = false
collectionView.backgroundColor = .secondarySystemFill
self.view.addSubview(collectionView!)
NSLayoutConstraint.activate([
collectionView.topAnchor.constraint(equalTo: view.safeAreaLayoutGuide.topAnchor),
collectionView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
collectionView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
collectionView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
])
self.view.backgroundColor = .tertiarySystemBackground
}
}
extension ViewController: UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
func createCompositionalLayout() -> UICollectionViewCompositionalLayout {
let itemSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let item = NSCollectionLayoutItem(layoutSize: itemSize)
let groupSize = NSCollectionLayoutSize(widthDimension: .fractionalWidth(1.0), heightDimension: .fractionalHeight(1.0))
let group = NSCollectionLayoutGroup.vertical(layoutSize: groupSize, subitems: [item])
let section = NSCollectionLayoutSection(group: group)
let maxScale = 1.0
let minScale = 0.7
section.visibleItemsInvalidationHandler = { items, offset, env in
for (index, item) in items.enumerated() {
if (index == 1) {
let distanceFromTop = (item.frame.midY - offset.y) - env.container.contentSize.height / 2.0
let alpha = 1 - (distanceFromTop / env.container.contentSize.height ) * 1.0
item.transform = CGAffineTransform.identity()
item.zIndex = 0
item.alpha = alpha
} else {
item.alpha = 1
item.zIndex = 1
item.transform = .identity
}
}
}
let config = UICollectionViewCompositionalLayoutConfiguration()
config.scrollDirection = .vertical
let layout = UICollectionViewCompositionalLayout(section: section, configuration: config)
return layout
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return 40
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "HostingCollectionViewCell", for: indexPath) as! HostingCollectionViewCell
let render = UIGraphicsImageRenderer(size: CGSize(width: 200, height: 200))
cell.mastImage.image = render.image(actions: { (ctx) in
UIImage(named: "bookmark")?.draw(in: CGRect(origin: .zero, size: .zero))
})
cell.titleLbl.text = "If you need support post Rotation Support for Autosizing, Full-width UICollectionViewCells in Swift 4. \(indexPath.row)"
cell.descriptionLbl.text = "As of August 2020, we Americans are embroiled in an intensifying cold civil war, says Julian Zelizer . Zelizer: The left is an ominous force thanks to a mix of cynical calculation, intimidation, and strong-arm tactics . The left doesn't want peace and stability 2014 unless it's on its terms, which would amount to a statist construct, meaning jackhammering the American foundation and evisceration of Western values."
return cell
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return collectionView.bounds.size
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
NSLog("Geting called")
return 0
}
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
NSLog("Geting called")
return 0
}
}
class HostingCollectionViewCell: UICollectionViewCell {
var titleLbl: UILabel = {
let titleLabel = UILabel()
titleLabel.font = UIFont(name: "Optima-Bold", size: UIFontMetrics.default.scaledValue(for: 20))
titleLabel.numberOfLines = 4
titleLabel.translatesAutoresizingMaskIntoConstraints = false
return titleLabel
}()
var descriptionLbl: UILabel = {
let descriptionLbl = UILabel()
descriptionLbl.font = UIFont(name: "LaoSangamMN", size: UIFontMetrics.default.scaledValue(for: 18))
descriptionLbl.numberOfLines = 0
descriptionLbl.translatesAutoresizingMaskIntoConstraints = false
return descriptionLbl
}()
var mastImage: UIImageView = {
let _img = UIImageView()
_img.translatesAutoresizingMaskIntoConstraints = false
_img.backgroundColor = .blue
_img.contentMode = .scaleAspectFit
_img.clipsToBounds = true
return _img
}()
var bottomToolbar: UIView = {
let toolbar = UIView()
toolbar.backgroundColor = .tertiarySystemFill
toolbar.translatesAutoresizingMaskIntoConstraints = false
return toolbar
}()
var imgHeightConstraint: NSLayoutConstraint?
var aspectRation = 1.0 {
didSet {
if(imgHeightConstraint != nil) {
mastImage.removeConstraint(imgHeightConstraint!)
}
imgHeightConstraint = mastImage.heightAnchor.constraint(lessThanOrEqualTo: mastImage.widthAnchor, multiplier: CGFloat(1 / aspectRation))
NSLayoutConstraint.activate([imgHeightConstraint!])
}
}
override init(frame: CGRect) {
super.init(frame: frame)
self.contentView.backgroundColor = .secondarySystemBackground
self.contentView.addSubview(self.titleLbl)
self.contentView.addSubview(self.mastImage)
self.contentView.addSubview(self.descriptionLbl)
self.contentView.addSubview(self.bottomToolbar)
NSLayoutConstraint.activate([
self.mastImage.topAnchor.constraint(equalTo: self.contentView.safeAreaLayoutGuide.topAnchor),
self.mastImage.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
self.mastImage.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
])
NSLayoutConstraint.activate([
self.titleLbl.topAnchor.constraint(equalTo: self.mastImage.bottomAnchor, constant: 8),
self.titleLbl.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10),
self.titleLbl.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10),
])
NSLayoutConstraint.activate([
self.descriptionLbl.topAnchor.constraint(equalTo: self.titleLbl.bottomAnchor, constant: 8),
self.descriptionLbl.bottomAnchor.constraint(lessThanOrEqualTo: bottomToolbar.topAnchor, constant: -10),
self.descriptionLbl.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor, constant: 10),
self.descriptionLbl.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor, constant: -10),
])
let bottom = (UIApplication.shared.windows.first { $0.isKeyWindow }?.safeAreaInsets.bottom) ?? 0
NSLayoutConstraint.activate([
self.bottomToolbar.leadingAnchor.constraint(equalTo: self.contentView.leadingAnchor),
self.bottomToolbar.trailingAnchor.constraint(equalTo: self.contentView.trailingAnchor),
self.bottomToolbar.heightAnchor.constraint(equalToConstant: 44 + bottom),
self.bottomToolbar.bottomAnchor.constraint(equalTo: self.contentView.bottomAnchor),
])
self.mastImage.setContentHuggingPriority(.defaultHigh, for: .vertical)
self.mastImage.setContentHuggingPriority(.defaultHigh, for: .horizontal)
self.mastImage.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
self.mastImage.setContentCompressionResistancePriority(.defaultLow, for: .horizontal)
self.titleLbl.setContentCompressionResistancePriority(.required, for: .vertical)
self.descriptionLbl.setContentCompressionResistancePriority(.required, for: .vertical)
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
extension UIColor {
class var random: UIColor {
return UIColor(red: .random(in: 0...1), green: .random(in: 0...1), blue: .random(in: 0...1), alpha: 1.0)
}
}
和FractionallySizedBox
定义应用/父项大小的百分比。
widthFactor
答案 3 :(得分:5)
那是因为颤动不是大小。这是关于约束的。
通常我们有2个用例:
Padding
,它接受子约束并增加它。SizedBox
,但在strech模式下也是Column
,... RaisedButton
是第一个案例。这意味着它是定义它自己的高度/宽度的按钮。并且,根据材料规则,凸起的按钮大小是固定的。
您不希望出现这种行为,因此您可以使用第二种类型的窗口小部件来覆盖按钮约束。
无论如何,如果你需要这么多,可以考虑创建一个新的小部件来完成你的工作。或者使用具有高度属性的MaterialButton
。
答案 4 :(得分:5)
新按钮TextButton、ElevatedButton、OutlinedButton 等将以不同的方式进行更改。
我发现的一种方法来自 this article:您需要“收紧”按钮周围的约束框。
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Kindacode.com'),
),
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tightFor(width: 300, height: 200),
child: ElevatedButton(
child: Text('300 x 200'),
onPressed: () {},
),
),
));
}
答案 5 :(得分:4)
我建议使用MaterialButton,而不是像这样:
pymysql.connect(host='localhost', user='root', password="pass", db='db_name', charset='utf8', port=3306)
答案 6 :(得分:4)
在 Flutter 2.0 中,RaisedButton
已被弃用并由 ElevatedButton
取代。
考虑到这一点,为 ElevatedButton
提供自定义尺寸的更简洁的方法是 minimumSize
小部件的 ElevatedButton
属性。
输出
完整代码
ElevatedButton(
style: ElevatedButton.styleFrom(
primary: Colors.green,
onPrimary: Colors.white,
shadowColor: Colors.greenAccent,
elevation: 3,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(32.0)),
minimumSize: Size(100, 40), //////// HERE
),
onPressed: () {},
child: Text('Hey bro'),
)
注意:另外请记住,相同的方法可以分别用于 TextButton
和 OutlinedButton
等新小部件,分别使用 TextButton.styleFrom(minimumSize: Size(100, 40))
和 OutlinedButton.styleFrom(minimumSize: Size(100, 40))
.
答案 7 :(得分:3)
将RaisedButton包装在Container内,并为Container Widget赋予宽度。
例如
Container(
width : 200,
child : RaisedButton(
child :YourWidget ,
onPressed(){}
),
)
答案 8 :(得分:3)
您可以创建全局方法,例如在整个应用程序中使用的按钮。它将根据容器内的文本长度调整大小。 FittedBox小部件用于根据其内部的子项使小部件适合。
Widget primaryButton(String btnName, {@required Function action}) {
return FittedBox(
child: RawMaterialButton(
fillColor: accentColor,
splashColor: Colors.black12,
elevation: 8.0,
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(5.0)),
child: Container(
padding: EdgeInsets.symmetric(horizontal: 20.0, vertical: 13.0),
child: Center(child: Text(btnName, style: TextStyle(fontSize: 18.0))),
),
onPressed: () {
action();
},
),
);
}
如果您希望按钮具有特定的宽度和高度,则可以使用RawMaterialButton的约束属性来提供按钮的最小最大宽度和高度
constraints: BoxConstraints(minHeight: 45.0,maxHeight:60.0,minWidth:20.0,maxWidth:150.0),
答案 9 :(得分:3)
使用Media Query为您的解决方案明智地使用宽度,无论在大屏幕还是大屏幕上,宽度都相同
Container(
width: MediaQuery.of(context).size.width * 0.5, // Will take 50% of screen space
child: RaisedButton(
child: Text('Go to screen two'),
onPressed: () => null
),
)
您也可以将类似的解决方案应用于SizeBox
。
答案 10 :(得分:2)
这段代码将帮助您更好地解决您的问题,因为我们不能直接为RaisedButton指定宽度,我们可以为其子级指定宽度
double width = MediaQuery.of(context).size.width;
var maxWidthChild = SizedBox(
width: width,
child: Text(
StringConfig.acceptButton,
textAlign: TextAlign.center,
));
RaisedButton(
child: maxWidthChild,
onPressed: (){},
color: Colors.white,
);
答案 11 :(得分:1)
如果要全局更改所有RaisedButton
的高度和minWidth,则可以在ThemeData
内覆盖MaterialApp
:
@override
Widget build(BuildContext context) {
return MaterialApp(
...
theme: ThemeData(
...
buttonTheme: ButtonThemeData(
height: 46,
minWidth: 100,
),
));
}
答案 12 :(得分:1)
您需要使用扩展窗口小部件。但是,如果您的按钮位于一列上,则“扩展小部件”将填充该列的其余部分。因此,您需要将扩展小部件括在一行中。
Row(children: <Widget>[
Expanded(
flex: 1,
child: RaisedButton(
child: Text("Your Text"),
onPressed: _submitForm,
),
),),])
答案 13 :(得分:1)
这对我有用。 Container 提供高度,而 FractionallySizedBox 提供 RaisedButton 的宽度。
Container(
height: 50.0, //Provides height for the RaisedButton
child: FractionallySizedBox(
widthFactor: 0.7, ////Provides 70% width for the RaisedButton
child: RaisedButton(
onPressed: () {},
),
),
),
答案 14 :(得分:0)
我们使用 Row 或 Column、Expanded、Container 和元素来使用示例 RaisedButton
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.start,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 10.0),
),
Row(
children: <Widget>[
Expanded(
flex: 2, // we define the width of the button
child: Container(
// height: 50, we define the height of the button
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RaisedButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
textColor: Colors.white,
color: Colors.blue,
onPressed: () {
// Method to execute
},
child: Text('Copy'),
),
),
),
),
Expanded(
flex: 2, // we define the width of the button
child: Container(
// height: 50, we define the height of the button
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 10.0),
child: RaisedButton(
materialTapTargetSize: MaterialTapTargetSize.shrinkWrap,
textColor: Colors.white,
color: Colors.green,
onPressed: () {
// Method to execute
},
child: Text('Paste'),
),
),
),
),
],
),
],
),
),
答案 15 :(得分:0)
SizedBox(
width: double.infinity,
child: ElevatedButton(
child: Text("FULL WIDTH"),
onPressed: () {},
),
),
使用 ElevatedButton,因为 RaisedButton 已被弃用
答案 16 :(得分:0)
如果您在Column()中有一个按钮,并且希望该按钮采用最大宽度,请设置:
crossAxisAlignment:CrossAxisAlignment.stretch
在“列”窗口小部件中。现在,此Column()下的所有内容都将具有最大可用宽度
答案 17 :(得分:0)
如果您不想删除所有设置的按钮主题。
ButtonTheme.fromButtonThemeData(
data: Theme.of(context).buttonTheme.copyWith(
minWidth: 200.0,
height: 100.0,,
)
child: RaisedButton(
onPressed: () {},
child: Text("test"),
),
);
答案 18 :(得分:0)
尝试一下
Expanded(
child: RaisedButton(
onPressed: _onButtonPressed,
child: Text('Button1')
)
)
答案 19 :(得分:0)
在我的情况下,我使用margin来更改大小:
Container(
margin: EdgeInsets.all(10),
// or margin: EdgeInsets.only(left:10, right:10),
child: RaisedButton(
padding: EdgeInsets.all(10),
shape: RoundedRectangleBorder(borderRadius:
BorderRadius.circular(20)),
onPressed: () {},
child: Text("Button"),
),
),
答案 20 :(得分:0)
让我与“匹配父级”作为“提升”按钮的首选方式是用“容器”包装它。 下面是示例代码。
Container(
width: double.infinity,
child: RaisedButton(
onPressed: () {},
color: Colors.deepPurpleAccent[100],
child: Text(
"Continue",
style: TextStyle(color: Colors.white),
),
),
)
答案 21 :(得分:0)
您可以按照评论中的意见进行操作,也可以节省精力并使用RawMaterialButton进行操作。它拥有一切,您可以将边框更改为圆形 还有很多其他属性。 ex shape(增加半径以具有更多的圆形)
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),//ex add 1000 instead of 25
,您可以使用GestureDetector来使用想要的任何形状作为按钮,GestureDetector是一个小部件,并在child属性下接受另一个小部件。 就像这里的另一个例子
GestureDetector(
onTap: () {//handle the press action here }
child:Container(
height: 80,
width: 80,
child:new Card(
color: Colors.blue,
shape: new RoundedRectangleBorder(borderRadius: BorderRadius.circular(25)),
elevation: 0.0,
child: Icon(Icons.add,color: Colors.white,),
),
)
)
答案 22 :(得分:0)
如果您希望RainseButton
占用父空间,请尝试Expanded Widget
答案 23 :(得分:-2)
全角按钮的简短解决方案:
Row(
children: [
Expanded(
child: ElevatedButton(...),
),
],
)