我有一个Flutter项目,其中有两个文本字段和一个用于输入值9的按钮,例如每个文本字段。
每个文本字段都有一个不同的控制器。
步骤:选择第一个文本字段,单击一个按钮,选择第二个文本字段,然后单击同一个按钮。
有两个问题:
1.如何为每个文本字段重用同一个按钮
1.如何判断选择了哪个文本字段
我写了下面的演示代码.请指教.谢谢
演示代码:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
TextEditingController mc = TextEditingController();
TextEditingController mc2 = TextEditingController();
clickButton(){
//click button to insert 9 into each field when a field is selected
//Please advice what code to add here
}
@override
Widget build(BuildContext context) {
Widget space = SizedBox(width: 100, height: 5, child: Text(""));
Widget myinput = TextField(controller: mc,keyboardType: TextInputType.number ,decoration: InputDecoration(border: OutlineInputBorder(), labelText: 'Number'));
Widget myinput2 = TextField(controller: mc2,keyboardType: TextInputType.number,decoration: InputDecoration(border: OutlineInputBorder(), labelText: 'Number'));
Widget btn1 = ElevatedButton(onPressed: clickButton, child: Text('9'));
return MaterialApp(
home: Scaffold(
resizeToAvoidBottomInset: false,
body: SingleChildScrollView(
scrollDirection: Axis.vertical,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Container(
padding: const EdgeInsets.all(5),
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
space,
myinput,
space,
myinput2,
space,
btn1,
space
],
),
),
),
],
),
),
),
);
}
}
1条答案
按热度按时间c86crjj01#
在该状态下,可以创建两个
FocusNode
,即:您可以将它们分配给每个
TextField
,即:在
clickButton
方法中,可以使用hasFocus
属性检查哪个FocusNode具有焦点。下面是一个完整的工作示例: