![](/img/trans.png)
[英]How can I pass flutter textediting controller value from one stateless widget to another stateless widget
[英]How to pass data to stateless widget calling from another stateless widget?
我試圖將一些顏色信息從一個小部件傳遞到另一個小部件,但我無法在目標小部件中獲得該顏色。 我想構建一個包含一些 UI 代碼的類,然后在我的主小部件中調用這個類,這樣我就不必再次重復代碼,但我無法傳遞數據,這是我正在處理的代碼:我做錯了什么?
void main(List<String> args) => runApp(const MyApp());
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData.dark(),
home: Scaffold(
appBar: AppBar(
title: const Text('Stateless/Clean Code'),
),
body: const StatelessOne(),
),
);
}
}
class StatelessOne extends StatelessWidget {
const StatelessOne({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
const Text(
'Widget color can be customised without \nhaving to retype the entire code'),
StatelessTwo(key: key, param: Colors.green),
StatelessTwo(key: key, param: Colors.pink),
StatelessTwo(key: key, param: Colors.blue),
StatelessTwo(key: key, param: Colors.orange),
],
),
);
}
}
class StatelessTwo extends StatelessWidget {
StatelessTwo({Key? key, @required param}) : super(key: key);
final Map param = {};
@override
Widget build(BuildContext context) {
return Container(
height: 120,
width: 250,
color: param['color'],
child: Center(child: Text('Your Repetitive Widget $key')),
);
}
}
簡單的方法將是
class StatelessTwo extends StatelessWidget {
final Color color;
StatelessTwo({Key? key, @required this.color}) : super(key: key);
-----
color: color, //use
傳遞 color StatelessTwo(key: key, color: Colors.green),
並且似乎您正在傳遞相同的key
,避免它對於 Ui-logic 不是必需的。 很可能,您不需要傳遞key
,如果您仍然想傳遞使用UinqueKey()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.