How can I access a variable value from one stateful widget class to another stateful widget class. Also both widget classes are in different .dart files.
This is screen.dart having the variable "List points". I want to use it in home.dart.
class Draw extends StatefulWidget {
const Draw({Key? key}) : super(key: key);
#override
_DrawState createState() => _DrawState();
}
class _DrawState extends State<Draw> {
List points = [];
#override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
Offset localPos = details.localPosition;
setState(() {
if (localPos.dx >= 0 &&
localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
localPos.dy >= 0 &&
localPos.dy <= MediaQuery.of(context).size.height * 0.5)
points.add(localPos);
else {
points.add(null);
}
});
},
onPanEnd: (DragEndDetails details) {
points.add(null);
},
child: CustomPaint(
painter: Painter(points: points),
),
);
}
}
...rest of code
This is home.dart
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.yellowAccent,
onPressed: () {
setState(() {
});
},
child: Icon(
Icons.restore_page,
color: Colors.black,
),
),
backgroundColor: Colors.grey[300],
appBar: AppBar(
backgroundColor: Colors.yellowAccent,
title: Text(
"Digit Recognizer",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: Center(
child: Column(
children: [
SizedBox(
height: 15,
),
Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width * 0.8,
decoration: BoxDecoration(
color: Colors.white, border: Border.all(color: Colors.black)),
child: Draw(),
),
...rest of code
I want to access the "points" from screen.dart variable inside the floatingActionButton's on pressed() function in home.dart.
You can place both of these widgets in the same file and then create points as a global Variable, so
List points = [];
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.yellowAccent,
onPressed: () {
setState(() {
print(points);
});
},
child: Icon(
Icons.restore_page,
color: Colors.black,
),
),
backgroundColor: Colors.grey[300],
appBar: AppBar(
backgroundColor: Colors.yellowAccent,
title: Text(
"Digit Recognizer",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: Center(
child: Column(
children: [
SizedBox(
height: 15,
),
Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width * 0.8,
decoration: BoxDecoration(
color: Colors.white, border: Border.all(color: Colors.black)),
child: Draw(),
),
...rest of code
class Draw extends StatefulWidget {
const Draw({Key? key}) : super(key: key);
#override
_DrawState createState() => _DrawState();
}
class _DrawState extends State<Draw> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
Offset localPos = details.localPosition;
setState(() {
if (localPos.dx >= 0 &&
localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
localPos.dy >= 0 &&
localPos.dy <= MediaQuery.of(context).size.height * 0.5)
points.add(localPos);
else {
points.add(null);
}
});
},
onPanEnd: (DragEndDetails details) {
points.add(null);
},
child: CustomPaint(
painter: Painter(points: points),
),
);
}
}
...rest of code
Usually I would not even create a different statefulw idget for this case but I am guessing you are doing it for some other reason. Creating a global variable allows it to be accessed from anywhere\
A better way of implementing the first answer might be this but you'll have to see if it works.
class Home extends StatefulWidget {
const Home({Key? key}) : super(key: key);
#override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
Widget drawWidget = Container();
#override
void initState(){
super.initState();
drawWidget = Draw();
}
#override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton(
backgroundColor: Colors.yellowAccent,
onPressed: () {
setState(() {
print(drawWidget.points);
});
},
child: Icon(
Icons.restore_page,
color: Colors.black,
),
),
backgroundColor: Colors.grey[300],
appBar: AppBar(
backgroundColor: Colors.yellowAccent,
title: Text(
"Digit Recognizer",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
),
body: Center(
child: Column(
children: [
SizedBox(
height: 15,
),
Container(
height: MediaQuery.of(context).size.height * 0.5,
width: MediaQuery.of(context).size.width * 0.8,
decoration: BoxDecoration(
color: Colors.white, border: Border.all(color: Colors.black)),
child: drawWidget,
),
...rest of code
And in drawWidget
class Draw extends StatefulWidget {
const Draw({Key? key}) : super(key: key);
List points = [];
#override
_DrawState createState() => _DrawState();
}
class _DrawState extends State<Draw> {
#override
Widget build(BuildContext context) {
return GestureDetector(
onPanUpdate: (DragUpdateDetails details) {
Offset localPos = details.localPosition;
setState(() {
if (localPos.dx >= 0 &&
localPos.dx <= MediaQuery.of(context).size.width * 0.8 &&
localPos.dy >= 0 &&
localPos.dy <= MediaQuery.of(context).size.height * 0.5)
widget.points.add(localPos);
else {
widget.points.add(null);
}
});
},
onPanEnd: (DragEndDetails details) {
widget.points.add(null);
},
child: CustomPaint(
painter: Painter(points: widget.points),
),
);
}
}
...rest of code
Hope it helps
The print statement in each code shows how to access
class stful1{
//create state method
}
class stful1 extends state{
//Widget build method
//data is actual data you want to send
Navigator.push(context,MaterialPageRoute((context)=>stful2(data)))
}
//stful2
class stful2{
//accept data in constructor
dataType data;
stful2(this.data);
//create state method
}
class stful2 extends state{
//Widget build method
//access like widget.data
}
Related
I want to drag and drop my custom widget with gesture detector. It is showing x- direction and y- direction values but not dragging to anywhere on screen.
Here is my code:
layoutpage:
SizedBox(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Stack(
children: _layoutProvider.tables
.map(
(SectionTable sTable) => Positioned(
top: sTable.top,
left: sTable.left,
child: LayoutWidget(
width: sTable.width,
height: sTable.height,
type: sTable.type.index,
name: sTable.name,
left: sTable.left,
top: sTable.top,
rotate: sTable.rotate,
color: sTable.order != null
? Colors.green
: Colors.grey,
seats: sTable.seats,
),
),
)
.toList()),
),
LayoutWidget:
class LayoutWidget extends StatefulWidget {
late double width;
late double height;
late double left;
late double top;
LayoutWidget({
Key? key,
required this.width,
required this.height,
required this.left,
required this.top,
}) : super(key: key);
#override
State<StatefulWidget> createState() => _LayoutWidgetState();
}
class _LayoutWidgetState extends State<LayoutWidget> {
#override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
RotationTransition(
turns: widget.type == 0
? const AlwaysStoppedAnimation(0)
: AlwaysStoppedAnimation(rotationValue / 360),
child: GestureDetector(
onPanUpdate: (details) {
widget.top = widget.top+ details.delta.dy;
widget.left = widget.left+ details.delta.dx;
setState(() {
});
},
onTap: () {
setState(() {
showMenu = !showMenu;
});
},
child: myWidget()
}
Can anyone help why i am unable to drag on screen. Thanks.
I hope you you can get Idea from this code. In this code you can drag Container anywhere in the Screen and set it. And also check this Gesture Detector Overview for Gesture Detector detail.
import 'package:flutter/cupertino.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
class GestureDetectorPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
color: Colors.grey[100],
width: double.infinity,
height: double.infinity,
child: MainContent(),
),
);
}
}
class MainContent extends StatefulWidget {
#override
_MainContentState createState() => _MainContentState();
}
class _MainContentState extends State<MainContent> {
GlobalKey key = GlobalKey();
String dragDirection = '';
String startDXPoint = '50';
String startDYPoint = '50';
String dXPoint;
String dYPoint;
String velocity;
#override
Widget build(BuildContext context) {
return GestureDetector(
onHorizontalDragStart: _onHorizontalDragStartHandler,
onVerticalDragStart: _onVerticalDragStartHandler,
onHorizontalDragUpdate: _onDragUpdateHandler,
onVerticalDragUpdate: _onDragUpdateHandler,
onHorizontalDragEnd: _onDragEnd,
onVerticalDragEnd: _onDragEnd,
dragStartBehavior: DragStartBehavior.start, // default
behavior: HitTestBehavior.translucent,
child: Stack(
children: [
Positioned(
left: double.parse(this.startDXPoint),
top: double.parse(this.startDYPoint),
child: Container(
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(100)
),
child: Center(
child: Padding(
padding: const EdgeInsets.all(20),
child: Text('Draggable', style: TextStyle(fontSize: 14, color: Colors.white),),
),
),
)
),
],
),
);
}
void _onHorizontalDragStartHandler(DragStartDetails details) {
setState(() {
this.dragDirection = "HORIZONTAL";
this.startDXPoint = '${details.globalPosition.dx.floorToDouble()}';
this.startDYPoint = '${details.globalPosition.dy.floorToDouble()}';
});
}
/// Track starting point of a vertical gesture
void _onVerticalDragStartHandler(DragStartDetails details) {
setState(() {
this.dragDirection = "VERTICAL";
this.startDXPoint = '${details.globalPosition.dx.floorToDouble()}';
this.startDYPoint = '${details.globalPosition.dy.floorToDouble()}';
});
}
void _onDragUpdateHandler(DragUpdateDetails details) {
setState(() {
this.dragDirection = "UPDATING";
this.startDXPoint = '${details.globalPosition.dx.floorToDouble()}';
this.startDYPoint = '${details.globalPosition.dy.floorToDouble()}';
});
}
/// Track current point of a gesture
void _onHorizontalDragUpdateHandler(DragUpdateDetails details) {
setState(() {
this.dragDirection = "HORIZONTAL UPDATING";
this.dXPoint = '${details.globalPosition.dx.floorToDouble()}';
this.dYPoint = '${details.globalPosition.dy.floorToDouble()}';
this.velocity = '';
});
}
/// Track current point of a gesture
void _onVerticalDragUpdateHandler(DragUpdateDetails details) {
setState(() {
this.dragDirection = "VERTICAL UPDATING";
this.dXPoint = '${details.globalPosition.dx.floorToDouble()}';
this.dYPoint = '${details.globalPosition.dy.floorToDouble()}';
this.velocity = '';
});
}
/// What should be done at the end of the gesture ?
void _onDragEnd(DragEndDetails details) {
double result = details.velocity.pixelsPerSecond.dx.abs().floorToDouble();
setState(() {
this.velocity = '$result';
});
}
}
You can use the Draggable widget instead. Please try this
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatefulWidget(),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
int acceptedData = 0;
#override
Widget build(BuildContext context) {
return Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
Draggable<int>(
// Data is the value this Draggable stores.
data: 10,
feedback: Container(
color: Colors.deepOrange,
height: 100,
width: 100,
child: const Icon(Icons.directions_run),
),
childWhenDragging: Container(
height: 100.0,
width: 100.0,
color: Colors.pinkAccent,
child: const Center(
child: Text('Child When Dragging'),
),
),
child: Container(
height: 100.0,
width: 100.0,
color: Colors.lightGreenAccent,
child: const Center(
child: Text('Draggable'),
),
),
),
DragTarget<int>(
builder: (
BuildContext context,
List<dynamic> accepted,
List<dynamic> rejected,
) {
return Container(
height: 100.0,
width: 100.0,
color: Colors.cyan,
child: Center(
child: Text('Value is updated to: $acceptedData'),
),
);
},
onAccept: (int data) {
setState(() {
acceptedData += data;
});
},
),
],
);
}
}
I have this error when I navigate from one page to another page using getx library, in first page I use indexed stack and second page using scaffold, I don't know what to do. Please help me solve this problem, I found many solutions in here but these does not same my problem.
First page:
class HomePage extends StatefulWidget {
HomePage({Key? key}) : super(key: key);
static String route = '/home';
final ScrollController _scrollController = ScrollController();
#override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
bool _isVisible = true;
void _hideFloationgButton(UserScrollNotification notification) {
final ScrollDirection direction = notification.direction;
setState(() {
if (direction == ScrollDirection.reverse) {
_isVisible = false;
} else if (direction == ScrollDirection.forward) {
_isVisible = true;
}
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xFFEDF0F3),
appBar: HomeAppBar('DAK'),
body: NotificationListener<UserScrollNotification>(
onNotification: (notification) {
_hideFloationgButton(notification);
return true;
},
child: SingleChildScrollView(
controller: widget._scrollController,
child: Column(
children: const [
StoryList(),
SizedBox(
height: 30,
),
SocialList(),
SizedBox(
height: 30,
),
MiddleNavList(),
SizedBox(
height: 30,
),
PostList(),
],
),
),
),
floatingActionButton: Visibility(
visible: _isVisible,
child: FloatingActionButton(
backgroundColor: prototypeColor,
onPressed: () {
Get.toNamed(Routes.POST);
},
child: const Icon(
Icons.add_box,
color: Colors.white,
),
)));
}
}
And the second page:
class PostPage extends StatelessWidget {
const PostPage({Key? key}) : super(key: key);
static String route = '/post';
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: backgroundColor,
appBar: AppBar(
leading: InkWell(
onTap: () {
Get.back();
},
child: const Icon(
Icons.arrow_back_ios,
color: accentColor,
),
),
title: const Text(
'Create post',
style: TextStyle(color: accentColor),
),
backgroundColor: backgroundColor,
elevation: 0,
),
body: const PostBody(),
);
}
}
I asked this question in this link Transition with futter move object
how i can make movig an object with AnimatedPositioned ? if i want an object move with a value = 1, or a value = 10
or something like that:
i = 0;
i++;
or
i = 0;
i = i + 10;
how i can do that with AnimatedPositioned
You only need to update position value from your AnimatedPositioned:
AnimatedPositioned(
width: selected ? 200.0 : 50.0,
height: selected ? 50.0 : 200.0,
top: selected ? 50.0 : 150.0,
duration: const Duration(seconds: 2),
curve: Curves.fastOutSlowIn,
child: GestureDetector(
onTap: () {
setState(() {
selected = !selected;
});
},
child: Container(
color: Colors.blue,
child: const Center(child: Text('Tap me')),
),
),
)
Just change that values to yours.
Full example:
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
#override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const Center(
child: MyStatefulWidget(),
),
),
);
}
}
class MyStatefulWidget extends StatefulWidget {
const MyStatefulWidget({Key? key}) : super(key: key);
#override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
class _MyStatefulWidgetState extends State<MyStatefulWidget> {
bool selected = false;
#override
Widget build(BuildContext context) {
return SizedBox(
width: 200,
height: 350,
child: Stack(
children: <Widget>[
AnimatedPositioned(
width: selected ? 200.0 : 50.0,
height: selected ? 50.0 : 200.0,
top: selected ? 50.0 : 150.0,
duration: const Duration(seconds: 2),
curve: Curves.fastOutSlowIn,
child: GestureDetector(
onTap: () {
setState(() {
selected = !selected;
});
},
child: Container(
color: Colors.blue,
child: const Center(child: Text('Tap me')),
),
),
),
],
),
);
}
}
Info: https://api.flutter.dev/flutter/widgets/AnimatedPositioned-class.html
Looking for a way to implement a button that can be toggled back and forth between favorites and history. Is there a way to do this in flutter.
You can try using a custom widget like this one below:
toggle_button.dart
import 'package:flutter/material.dart';
class ToggleButton extends StatefulWidget {
final double width;
final double height;
final String leftDescription;
final String rightDescription;
final Color toggleColor;
final Color toggleBackgroundColor;
final Color toggleBorderColor;
final Color inactiveTextColor;
final Color activeTextColor;
final double _leftToggleAlign = -1;
final double _rightToggleAlign = 1;
final VoidCallback onLeftToggleActive;
final VoidCallback onRightToggleActive;
const ToggleButton(
{Key? key,
required this.width,
required this.height,
required this.toggleBackgroundColor,
required this.toggleBorderColor,
required this.toggleColor,
required this.activeTextColor,
required this.inactiveTextColor,
required this.leftDescription,
required this.rightDescription,
required this.onLeftToggleActive,
required this.onRightToggleActive})
: super(key: key);
#override
_ToggleButtonState createState() => _ToggleButtonState();
}
class _ToggleButtonState extends State<ToggleButton> {
double _toggleXAlign = -1;
late Color _leftDescriptionColor;
late Color _rightDescriptionColor;
#override
void initState() {
super.initState();
_leftDescriptionColor = widget.activeTextColor;
_rightDescriptionColor = widget.inactiveTextColor;
}
#override
Widget build(BuildContext context) {
return Container(
width: widget.width,
height: widget.height,
decoration: BoxDecoration(
color: widget.toggleBackgroundColor,
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
border: Border.all(color: widget.toggleBorderColor),
),
child: Stack(
children: [
AnimatedAlign(
alignment: Alignment(_toggleXAlign, 0),
duration: Duration(milliseconds: 300),
child: Container(
width: widget.width * 0.5,
height: widget.height,
decoration: BoxDecoration(
color: widget.toggleColor,
borderRadius: BorderRadius.all(
Radius.circular(50.0),
),
),
),
),
GestureDetector(
onTap: () {
setState(
() {
_toggleXAlign = widget._rightToggleAlign;
_leftDescriptionColor = widget.inactiveTextColor;
_rightDescriptionColor = widget.activeTextColor;
},
);
widget.onRightToggleActive();
},
child: Align(
alignment: Alignment(-1, 0),
child: Container(
width: widget.width * 0.5,
color: Colors.transparent,
alignment: Alignment.center,
child: Text(
widget.leftDescription,
style: TextStyle(
color: _leftDescriptionColor,
fontWeight: FontWeight.bold),
),
),
),
),
GestureDetector(
onTap: () {
setState(
() {
_toggleXAlign = widget._leftToggleAlign;
_leftDescriptionColor = widget.activeTextColor;
_rightDescriptionColor = widget.inactiveTextColor;
},
);
widget.onLeftToggleActive();
},
child: Align(
alignment: Alignment(1, 0),
child: Container(
width: widget.width * 0.5,
color: Colors.transparent,
alignment: Alignment.center,
child: Text(
widget.rightDescription,
style: TextStyle(
color: _rightDescriptionColor,
fontWeight: FontWeight.bold),
),
),
),
),
],
),
);
}
}
main.dart
import 'package:flutter/material.dart';
import 'package:stackovfl_70777885/toggle_button.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: const MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
#override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Container(
padding: EdgeInsets.all(10.0),
child: ToggleButton(
width: 300.0,
height: 60.0,
toggleBackgroundColor: Colors.white,
toggleBorderColor: (Colors.grey[350])!,
toggleColor: (Colors.indigo[900])!,
activeTextColor: Colors.white,
inactiveTextColor: Colors.grey,
leftDescription: 'FAVORITES',
rightDescription: 'HISTORY',
onLeftToggleActive: () {
print('left toggle activated');
},
onRightToggleActive: () {
print('right toggle activated');
},
),
),
);
}
}
This should result in the following:
The onLeftToggleActive(): () {} and onRightToggleActive() {} in main are triggered depending on where the slider moves.
Unable to change the width after "Transform.scale"?
In the following sample code, the red Container, do not change width after setting fitWidth(width of container) when pressing the floatingbutton.
Only if it is les than 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,
));
}
}
its works for me
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,
));
}
cheers...
try this,
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,
));
}
}
Give alignment(Align)
Transform.scale(
scale: 0.5,
child: Center( // or Align
child: Container(
color: Colors.red,
width: sizWidth,
height: 400,
),
),
)