首页 > 解决方案 > 颤动容器内元素的相对位置

问题描述

我有以下稍微修改的标准应用程序,其中按钮和结果放在一个容器中。

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: ...

标签: flutterdart

解决方案


对于屏幕的高度和宽度,您可以查看以下答案: 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()),

推荐阅读