問題描述
如何在 Flutter 中相對於另一個小部件定位小部件? (how can I position a widget relative to another in Flutter?)
我有一張圖片,我想在上面放置小圖片。我已經有了這些圖像相對於原始圖像的位置(寬度、高度、topLeftX、topLeftY、bottomRight..)。
我無法放置這些小圖像(由藍色框表示在下面的附加示例中)關於圖像。它們總是相對於整個屏幕定位。
這是我嘗試過的:
Stack(
children:[
Positioned(
top: 245,
left: 43,
width: 200,height: 200,child:Container(color:Colors.blue)),
Container(
child:PhotoView(imageProvider: AssetImage("lib/assets/3D_example_2.png"),
controller: controller,
)),])
我怎樣才能相對於圖像放置我的圖像(矩形)?我還想相對於原始圖像縮放這些圖像的寬度和高度 允許它們在縮放時與原始圖像一起移動..
知道如何做到這一點嗎?
謝謝!
參考解法
方法 1:
import 'package:flutter/material.dart';
void main() {
runApp(
MaterialApp(
debugShowCheckedModeBanner: false,
home: HomePage(),
),
);
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(
"Rough Work",
),
centerTitle: true,
),
body: Stack(
overflow: Overflow.visible,
children: [
Positioned(
top: 200,
left: 100,
child: Container(
height: 200,
width: 200,
color: Colors.teal,
child: Stack(
children: [
Positioned(
top: 12,
child: Container(
height: 150,
width: 150,
child: Image(
image: NetworkImage(
"https://images.pexels.com/photos/736230/pexels‑photo‑736230.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"),
),
),
),
],
),
),
),
],
),
);
}
}
</code></pre>
方法 2:
I would suggest adding the width and height of the boxes to the Container widget instead, but apart from that, there seems to be no problem with your code. So I thing the behavior can be related to a parent widget:
Checkout the following code:
import 'package:flutter/material.dart';
void main() => runApp(
MaterialApp(home: HomePage(),
theme: ThemeData.light()
),
);
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Stack(
overflow: Overflow.visible,
children: [
Positioned(
top: 245,
left: 43,
child: Container(
color: Colors.lightGreen,
width: 100,
height: 100,
),
),
Positioned(
top: ‑50,
left: 120,
child: Container(
color: Colors.redAccent,
width: 100,
height: 100,
),
),
Container(
color: Colors.indigo,
width: 200,
height: 200,
),
],
)
],
),
),
);
}
}
(by DCodes、Ajay Gajera、Rodrigo Cardozo)
參考文件