[英]Pass values from one class to another flutter
我正在嘗試計算立方體的面積。 為此,我創建了一個 class,其中包含一個 slider 以獲取高度或寬度值。 但是我不知道如何將高度和寬度這兩個值聯合起來進行計算,或者如何將這個class的值傳遞到我的主頁。 如何將計算保存在變量中?
代碼主頁:
class HomePage extends StatefulWidget {
const HomePage({super.key, required this.title});
final String title;
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
late double heightScreen, widthScreen;
@override
Widget build(BuildContext context) {
heightScreen =
MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top;
widthScreen = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: const Text("Test "),
),
body: Column(
children: [
SizedBox(
height: 20,
),
ChooseArea(slidString: "Height"),
ChooseArea(slidString: "Width"),
],
),
);
}
}
選擇地區:
class ChooseArea extends StatefulWidget {
ChooseArea({
Key? key,
required this.slidString,
}) : super(key: key);
final String slidString;
@override
State<ChooseArea> createState() => _ChooseAreaState();
}
class _ChooseAreaState extends State<ChooseArea> {
double valueBottom = 1;
@override
Widget build(BuildContext context) {
return Column(children: [
Row(
children: [
Padding(
padding: const EdgeInsets.only(left: 7),
child: Text(widget.slidString))
],
),
Row(children: [
SizedBox(
width: 250,
child: Slider(
value: valueBottom,
label: "${valueBottom.toStringAsFixed(2)} m",
divisions: 100,
min: 1,
max: 50,
onChanged: (value) => setState(() => valueBottom = value)),
),
SizedBox(width: 20),
Text("${valueBottom.toStringAsFixed(2)} m")
])
]);
}
}
您可以使用findAncestorStateOfType
,首先將您的HomePage
更改為:
class HomePage extends StatefulWidget {
const HomePage({super.key, required this.title});
final String title;
@override
State<HomePage> createState() => HomePageState();
static HomePageState? of(BuildContext context) =>
context.findAncestorStateOfType<HomePageState>();
}
class HomePageState extends State<HomePage> {
late double heightScreen, widthScreen;
double? heightArea, widthArea;
set heightValue(double value) {
heightArea = value;
print("heightArea = $heightArea");
}
set widthValue(double value) {
widthArea = value;
print("widthArea = $widthArea");
}
@override
Widget build(BuildContext context) {
heightScreen =
MediaQuery.of(context).size.height - MediaQuery.of(context).padding.top;
widthScreen = MediaQuery.of(context).size.width;
return Scaffold(
appBar: AppBar(
title: const Text("Test "),
),
body: Column(
children: [
SizedBox(
height: 20,
),
ChooseArea(slidString: "Height"),
ChooseArea(slidString: "Width"),
],
),
);
}
}
然后將您的 ChooseArea 的onChanged
更改為此:
Slider(
value: valueBottom,
label: "${valueBottom.toStringAsFixed(2)} m",
divisions: 100,
min: 1,
max: 50,
onChanged: (value) {
if (widget.slidString == "Width") {
HomePage.of(context)?.widthValue = value;
} else {
HomePage.of(context)?.heightValue = value;
}
setState(() => valueBottom = value);
})
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.