我已经成功地创建了下面的示例,其中当我尝试使用unfocus()时也尝试滚动到PageView的下一个索引时,它会弹回到页面视图中。
复制步骤:
但是,如果您注释掉unfocus(),它将按预期工作。
import 'package:flutter/material.dart';
final MainScreenViewModel model = MainScreenViewModel();
class MainScreenView extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: SafeArea(
child: Scaffold(
body: Column(
children: <Widget>[
Items(),
_PreviousNextButtons(),
],
),
),
));
}
}
class _PreviousNextButtons extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: [
RaisedButton(
onPressed: model.isFirstItem() ? null : () => model.previousItem(),
child: const Text("Previous"),
),
RaisedButton(
onPressed: () => model.nextItem(),
child: const Text("Next"),
)
],
);
}
}
class Items extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Expanded(
child: PageView(
physics: const NeverScrollableScrollPhysics(),
controller: model.pageController,
scrollDirection: Axis.vertical,
children: model.itemFormKeys.mapIndexed((item, index) {
return Form(
key: model.itemFormKeys[index],
child: Column(children: <Widget>[
Text(model.items[index]),
_NumberField(),
]),
);
}).toList()),
);
}
}
class _NumberField extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container(
width: 200,
height: 100,
child: TextFormField(
controller: TextEditingController(),
keyboardType:
const TextInputType.numberWithOptions(signed: true, decimal: true),
autofocus: false,
),
);
}
}
class MainScreenViewModel {
int _currentItemIndex = 0;
final PageController pageController = PageController();
final List<String> items = ["1", "2", "3"];
final List<GlobalKey<FormState>> itemFormKeys = [
GlobalKey<FormState>(),
GlobalKey<FormState>(),
GlobalKey<FormState>()
];
void previousItem() {
if (_currentItemIndex != 0) {
_currentItemIndex--;
pageController.animateToPage(
_currentItemIndex,
curve: Curves.linear,
duration: const Duration(milliseconds: 500),
);
}
}
void nextItem() {
FocusManager.instance.primaryFocus.unfocus();
_currentItemIndex++;
pageController.animateToPage(
_currentItemIndex,
curve: Curves.linear,
duration: const Duration(milliseconds: 500),
);
}
bool isFirstItem() => _currentItemIndex == 0;
}
extension IndexedIterable<E> on Iterable<E> {
Iterable<T> mapIndexed<T>(T Function(E, int) f) {
var i = 0;
return map((e) => f(e, i++));
}
}