Flutter Textfield cursor focus moves to another textfield when new widget appears with provider watch
Video
As shown in video, with provider watch, textfield cursor focus moves to the upper textfield when new Text widgets appear above the textfields.
This doesn't happen when Text widget appears below the textfield widgets.
Replacing if (testPvd.showA)
with Visibility widget does prevent the cursor from moving, however I still don't understand this happening.
Can anyone explain why this happens?
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
class TestWidget extends StatefulWidget {
const TestWidget({Key? key}) : super(key: key);
@override
State<TestWidget> createState() => _TestWidgetState();
}
class _TestWidgetState extends State<TestWidget> {
var controller1 = TextE开发者_JAVA百科ditingController();
var controller2 = TextEditingController();
var controller3 = TextEditingController();
var controller4 = TextEditingController();
@override
Widget build(BuildContext context) {
TestProvider testPvd = context.watch<TestProvider>();
return Scaffold(
body: ListView(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
padding: EdgeInsets.symmetric(vertical: 50, horizontal: 20),
children: [
Row(
children: [
InkWell(
child: Text('showA'),
onTap: () {
testPvd.updateToggleButton('A');
},
),
SizedBox(width: 20),
InkWell(
child: Text('showB'),
onTap: () {
testPvd.updateToggleButton('B');
},
),
],
),
SizedBox(height: 20),
if (testPvd.showA) Text('A'),
if (testPvd.showB) Text('B'),
SizedBox(height: 20),
TextField(controller: controller1),
TextField(controller: controller2),
TextField(controller: controller3),
TextField(controller: controller4),
// if (testPvd.showA) Text('A'),
// if (testPvd.showB) Text('B'),
],
),
);
}
}
class TestProvider with ChangeNotifier {
bool showA = false;
bool showB = false;
updateToggleButton(String value) {
if (value == 'A') showA = !showA;
if (value == 'B') showB = !showB;
notifyListeners();
}
}
Expected the cursor to stay on current textfield.
精彩评论