flutter - 颤动容器内元素的相对位置
问题描述
我有以下稍微修改的标准应用程序,其中按钮和结果放在一个容器中。
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,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: containerWidget()
),
);
}
}
class containerWidget extends StatefulWidget {
@override
_containerWidgetState createState() => _containerWidgetState();
}
class _containerWidgetState extends State<containerWidget> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Container(
color: Colors.red,
height : 300,
width : 300,
child:
Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
],
),
);
}
}
第一步,我想获取屏幕的宽度和大小,以设置容器小部件在屏幕内的相对位置。
在第二步中,我想修改 Container 小部件中 Button 的位置,这意味着要么
- 通过获取容器的绝对位置来设置按钮相对于屏幕大小的绝对位置
或者
- 通过设置容器内按钮的相对位置
Positioned(left: 30.0,
top: 50.0,
child: Container(
width: 100.0,
height: 80.0,
decoration: new BoxDecoration(color: Colors.red),
child: ...
解决方案
对于屏幕的高度和宽度,您可以查看以下答案: Flutter screen size
如果您想相对于父容器移动按钮,可以使用 Stack 小部件包装容器,并将容器和按钮设置为其子项(意味着您必须将按钮移到容器外),然后简单地包装带有 Positioned 小部件的按钮并使用参数right : , left : , top : , bottom : ,
来控制按钮相对于容器的位置
//for example, this means the container is 30px to the left and 50px from the top
Positioned(left: 30.0,
top: 50.0,
child: Container()),
推荐阅读
- android - Firebase Crashlytics 和 NDK 原生崩溃
- rest - 是否有一个开放源代码的集成平台,即使对于大量数据、无限运行和流动也是免费的?
- go - 如何检查在后台启动的进程是否仍在运行?
- django - 动态添加字段到 Django modelformset ManagementForm 数据丢失或被篡改
- javascript - 无法将 Button 值从子组件传递到父组件
- powershell - 如果使用 wmic 和 powershell 安装了特定程序,则查询远程机器
- java - 验证标签在另一个 Java 正则表达式中
- bitbucket - 如何使用 SCM Backup 恢复 Bitbucket Backup?
- python - 如何根据字符串中位置的值提取熊猫中的文本?
- php - 无法关闭 PDO 连接