最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

flutter - How to autofocus a list item widget programmatically from the parent of it? - Stack Overflow

programmeradmin5浏览0评论
class MyHome extends StatefulWidget {

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (context, index) => MyItem(index: index),
    );
  }

  void setFocusedIndex(int index) {
    // How to focus the item at the given index?
  }
}

class MyItem extends StatefulWidget {
  final int index;

  const MyItem({super.key, required this.index});

  @override
  State<MyItem> createState() => _MyItemState();
}

class _MyItemState extends State<MyItem> {
  final FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text('Item ${widget.index}'),
      focusNode: focusNode,
      onTap: () {
        focusNode.requestFocus();
      },
    );
  }

  @override
  void dispose() {
    focusNode.dispose();
    super.dispose();
  }
}
class MyHome extends StatefulWidget {

  @override
  State<MyHome> createState() => _MyHomeState();
}

class _MyHomeState extends State<MyHome> {

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: 10,
      itemBuilder: (context, index) => MyItem(index: index),
    );
  }

  void setFocusedIndex(int index) {
    // How to focus the item at the given index?
  }
}

class MyItem extends StatefulWidget {
  final int index;

  const MyItem({super.key, required this.index});

  @override
  State<MyItem> createState() => _MyItemState();
}

class _MyItemState extends State<MyItem> {
  final FocusNode focusNode = FocusNode();

  @override
  Widget build(BuildContext context) {
    return ListTile(
      title: Text('Item ${widget.index}'),
      focusNode: focusNode,
      onTap: () {
        focusNode.requestFocus();
      },
    );
  }

  @override
  void dispose() {
    focusNode.dispose();
    super.dispose();
  }
}
Share Improve this question asked yesterday Birju VachhaniBirju Vachhani 6,3734 gold badges24 silver badges44 bronze badges 1
  • Does MyItem has fixed height? – Md. Yeasin Sheikh Commented yesterday
Add a comment  | 

1 Answer 1

Reset to default 1

Flutter currently does not have implemented solution to scroll list view to make sure item is visible , but there is an ways to do it ,in case if your items has fixed height you can do that by scrollController.scrolTo , also Scrollable.ensureVisible() function also can help you.

发布评论

评论列表(0)

  1. 暂无评论