“ Transform.scale”之后无法更改宽度吗?
在下面的示例代码中,红色的Container,在按下浮动按钮时,在设置fitWidth(容器的宽度)后,不要更改宽度。
仅比MediaQuery.of(context).size.width少。
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: MyStatefulWidget(),
);
}
}
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
// State
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Matrix4 matrix = Matrix4.identity();
double fitWidth;
@override
void initState() {
fitWidth = 0;
super.initState();
}
double getSizeWidth(BuildContext context) {
if (fitWidth != 0) {
return fitWidth;
} else {
return MediaQuery.of(context).size.width;
}
}
Widget build(BuildContext context) {
var sizWidth = getSizeWidth(context);
print(sizWidth);
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
),
body: Transform.scale(
scale: 0.5,
child: Container(
color: Colors.red,
width: sizWidth,
height: 400,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
fitWidth = 800;
});
// Add your onPressed code here!
},
backgroundColor: Colors.green,
));
}
}
尝试一下,
class MyStatefulWidget extends StatefulWidget {
MyStatefulWidget({Key key}) : super(key: key);
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Matrix4 matrix = Matrix4.identity();
double widthScale = 0.0;
@override
void initState() {
super.initState();
}
double getSizeWidth(BuildContext context) {
if (widthScale != 0.0) {
return widthScale;
} else {
return 1.0;
}
}
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
),
body: Transform(
alignment: Alignment.center,
transform: new Matrix4.identity()..scale(getSizeWidth(context), 0.5),
child: Container(
color: Colors.red,
width: MediaQuery.of(context).size.width,
height: 400,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
widthScale = 0.5;
});
// Add your onPressed code here!
},
backgroundColor: Colors.green,
));
}
}
给出对齐(Align
)
Transform.scale(
scale: 0.5,
child: Center( // or Align
child: Container(
color: Colors.red,
width: sizWidth,
height: 400,
),
),
)
它对我有用
Widget build(BuildContext context) {
print(sizWidth);
return Scaffold(
appBar: AppBar(
title: const Text('Sample Code'),
),
body: Transform.scale(
scale: 0.5,
child: Container(
color: Colors.red,
width: fitWidth != 0?fitWidth:MediaQuery.of(context).size.width,
height: 400,
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
fitWidth = 800;
});
// Add your onPressed code here!
},
backgroundColor: Colors.green,
));
}
欢呼...