[英]Change TextField background Color based on the TextField state
我目前正在嘗試實現一個 TextField,它應該根據文本字段的 state 更改背景顏色(未聚焦,聚焦,錯誤)。
我試圖通過使用僅管理是否選擇 TextField 的 List 來實現這一點。 我使用 GestureDetector 來設置該值。 但這似乎太老套了,不能成為一個好的解決方案,尤其是因為點擊 TextField 並不是集中注意力的唯一方法。
在這一點上,我希望有一種方法可以獲取 TextField Widget 用來顯示適當邊框樣式的相同信息。 但我不確定是否可以訪問這些信息。 非常感謝您提供有關如何執行此操作的提示。
我也在想我可以為此使用 FocusScope,但我找不到在單個 TextFormField 上調用.hasFocus 的方法,因為它只顯示是否選擇了整個表單中的一個 TextFormField,而不是選擇哪個。
謝謝!
您可以在FocusScope
中使用FocusNode
或Focus
來實現類似的效果。 TextField
本身使用一個FocusNode
來確定它是否有焦點,然后在焦點 state 發生變化時動畫顏色變化。 這是使用Focus
和Builder
僅重建更改焦點的TextFields
的示例實現:
https://dartpad.dev/8488f470b166e4235b64d3ba568b6ba6?null_safety=true
import 'package:flutter/material.dart';
void main() => runApp(const MyApp());
/// This is the main application widget.
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
static const String _title = 'Flutter Code Sample';
@override
Widget build(BuildContext context) {
return MaterialApp(
title: _title,
home: Scaffold(
appBar: AppBar(title: const Text(_title)),
body: const MyStatelessWidget(),
),
);
}
}
/// This is the private State class that goes with MyStatefulWidget.
class MyStatelessWidget extends StatelessWidget {
const MyStatelessWidget();
@override
Widget build(BuildContext context) {
return FocusScope(
debugLabel: 'Scope',
autofocus: true,
child: Form(
child: Column(
children: [
Focus(
debugLabel: 'TextField1',
child: Builder(
builder: (BuildContext context) {
final FocusNode focusNode = Focus.of(context);
final bool hasFocus = focusNode.hasFocus;
return TextField(
decoration: InputDecoration(
fillColor: hasFocus ? Colors.green : Colors.white,
filled: true
)
);
},
),
),
Focus(
debugLabel: 'TextField2',
child: Builder(
builder: (BuildContext context) {
final FocusNode focusNode = Focus.of(context);
final bool hasFocus = focusNode.hasFocus;
return TextField(
decoration: InputDecoration(
fillColor: hasFocus ? Colors.green : Colors.white,
filled: true
)
);
}
)
)
],
),
),
);
}
}
您當然也可以直接使用FocusNode
。 為此,您可能必須將TextFields
包裝到StatefulWidget
中,然后向所使用的FocusNode
添加一個偵聽器,以便在焦點更改時觸發重建(使用setState
)。 但請注意,您需要管理此FocusNode
的生命周期。 從文檔中引用:
管理 FocusNode 意味着管理它的生命周期,監聽焦點的變化,並在需要時重新設置它的父節點,以保持焦點層次結構與小部件層次結構同步。 這個小部件為您完成所有這些事情。 如果您不使用 Focus 小部件並且需要自己進行操作,請參閱 FocusNode 以獲取有關節點管理所需的詳細信息的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.