颤振-如何以编程方式自动滚动到具有动态高度的索引 [英] flutter - How to auto scroll to index with dynamic height programmatically

查看:79
本文介绍了颤振-如何以编程方式自动滚动到具有动态高度的索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据Flutter的

解决方案

滚动到索引包

此软件包为Flutter可滚动小部件提供了用于固定/可变行高的滚动到索引机制.

这是一个小部件级别的库,意味着您可以在任何Flutter可滚动小部件中使用此机制.

用法

pubspec.yaml

  scroll_to_index:任意 

示例来自

因此它不能支持100%

Ref:

第一个屏幕记录代码

 //版权所有(C)2019 Potix Corporation.版权所有.//历史记录:2019年4月24日星期二09:29//作者:杰里·陈(Jerry Chen)将'dart:math'导入为数学;导入'package:flutter/material.dart';导入'package:scroll_to_index/scroll_to_index.dart';void main()=>runApp(MyApp());MyApp类扩展了StatelessWidget {//此小部件是您的应用程序的根.@override窗口小部件build(BuildContext context){返回MaterialApp(标题:滚动至索引演示",主题:ThemeData(primarySwatch:Colors.blue,),主页:MyHomePage(标题:滚动至索引演示"),);}}类MyHomePage扩展了StatefulWidget {MyHomePage({Key key,this.title}):超级(key:key);最终的字符串标题;@override_MyHomePageState createState()=>_MyHomePageState();}类_MyHomePageState扩展State< MyHomePage>{静态const maxCount = 100;最终随机数= math.Random();最终的scrollDirection = Axis.vertical;AutoScrollController控制器;List< List< int>>randomList;@override无效的initState(){super.initState();控制器= AutoScrollController(viewportBoundaryGetter:()=>Rect.fromLTRB(0,0,0,MediaQuery.of(context).padding.bottom),轴:scrollDirection);randomList = List.generate(maxCount,(index)=< int> [index,(1000 * random.nextDouble()).toInt()]);}@override窗口小部件build(BuildContext context){返回脚手架(appBar:AppBar(标题:文本(widget.title),),正文:ListView(scrollDirection:scrollDirection,控制器:控制器,子代:randomList.map< Widget>(((data){返回填充(填充:EdgeInsets.all(8),子级:_getRow(data [0],math.max(data [1] .toDouble(),50.0)),);}).toList(),),floatActionButton:FloatingActionButton(onPressed:_scrollToIndex,工具提示:增量",子级:Text(counter.toString()),),);}整数计数器= -1;未来_scrollToIndex()异步{setState((){计数器++;如果(计数器> = maxCount)计数器= 0;});等待controller.scrollToIndex(counter,preferredPosition:AutoScrollPosition.begin);controller.highlight(counter);}小部件_getRow(int index,double height){返回_wrapScrollTag(索引:索引,子代:集装箱(填充:EdgeInsets.all(8),对齐方式:Alignment.topCenter,高度:高度装饰:BoxDecoration(border:Border.all(颜色:Colors.lightBlue,宽度:4),borderRadius:BorderRadius.circular(12)),子代:文字('index:$ index,height:$ height'),));}小部件_wrapScrollTag({int index,小部件子级})=>AutoScrollTag(键:ValueKey(index),控制器:控制器,索引:索引,孩子:孩子,highlightColor:Colors.black.withOpacity(0.1),);} 

第二屏记录代码:

 //版权所有(C)2019 Potix Corporation.版权所有.//历史记录:2019年4月24日星期二09:29//作者:杰里·陈(Jerry Chen)将'dart:math'导入为数学;导入'package:flutter/material.dart';导入'package:scroll_to_index/scroll_to_index.dart';void main()=>runApp(MyApp());MyApp类扩展了StatelessWidget {//此小部件是您的应用程序的根.@override窗口小部件build(BuildContext context){返回MaterialApp(标题:滚动至索引演示",主题:ThemeData(primarySwatch:Colors.blue,),主页:MyHomePage(标题:滚动至索引演示"),);}}类MyHomePage扩展了StatefulWidget {MyHomePage({Key key,this.title}):超级(key:key);最终的字符串标题;@override_MyHomePageState createState()=>_MyHomePageState();}类_MyHomePageState扩展State< MyHomePage>{最终的scrollDirection = Axis.vertical;var rnd = math.Random();整数最小值= 50;最大整数= 200;AutoScrollController控制器;@override无效的initState(){super.initState();控制器= AutoScrollController(viewportBoundaryGetter:()=>Rect.fromLTRB(0,0,0,MediaQuery.of(context).padding.bottom),轴:scrollDirection);}@override窗口小部件build(BuildContext context){返回脚手架(appBar:AppBar(标题:文本(widget.title),),正文:ListView.builder(scrollDirection:scrollDirection,控制器:控制器,itemBuilder :(上下文,i)=>填充(填充:EdgeInsets.all(8),子级:_getRow(i,(min + rnd.nextInt(max-min)).toDouble()),),),floatActionButton:FloatingActionButton(onPressed:_scrollToIndex,工具提示:增量",子级:Text(counter.toString()),),);}整数计数器= -1;未来_scrollToIndex()异步{setState((){计数器++;});等待controller.scrollToIndex(counter,preferredPosition:AutoScrollPosition.begin);controller.highlight(counter);}小部件_getRow(int index,double height){返回_wrapScrollTag(索引:索引,子代:集装箱(填充:EdgeInsets.all(8),对齐方式:Alignment.topCenter,高度:高度装饰:BoxDecoration(边框:Border.all(颜色:Colors.lightBlue,宽度:4),borderRadius:BorderRadius.circular(12)),子代:文字('index:$ index,height:$ height'),));}Widget _wrapScrollTag({int index,Widget child})=>AutoScrollTag(键:ValueKey(index),控制器:控制器,索引:索引,孩子:孩子,highlightColor:Colors.black.withOpacity(0.1),);} 

According to Flutter's issue here , The Auto-Scroll to Index where each cell/item has dynamic height is currently not supported. I have tried another solution but no works.

so, What's a temporary solution to make ListView with AutoScroll for dynamic height?

Any Idea?

解决方案

Your question

so, What's a temporary solution to make ListView with AutoScroll for dynamic height?

Screen Record

solution

scroll-to-index package

This package provides the scroll to index mechanism for fixed/variable row height for Flutter scrollable widget.

This is a widget level library, means you can use this mechanism inside any Flutter scrollable widget.

Usage

pubspec.yaml

 scroll_to_index: any

Example From quire-io/scroll-to-index: scroll to index with fixed/variable row height inside Flutter scrollable widget

Usage - Controller

controller.scrollToIndex(index, preferPosition: AutoScrollPosition.begin)

Usage - ListView

ListView(
scrollDirection: scrollDirection,
controller: controller,
children: randomList.map<Widget>((data) {
    final index = data[0];
    final height = data[1];
    return AutoScrollTag(
    key: ValueKey(index),
    controller: controller,
    index: index,
    child: Text('index: $index, height: $height'),
    highlightColor: Colors.black.withOpacity(0.1),
    );
}).toList(),
)

Extra anunixercoder asked

Is this for finite or infinite list ?

Using ListView.builder to simulate an infinite list

    ListView.builder(
    scrollDirection: scrollDirection,
    controller: controller,
    itemBuilder: (context, i) => Padding(
      padding: EdgeInsets.all(8),
      child: _getRow(i, (min + rnd.nextInt(max - min)).toDouble()),
    ),

It got 18 right of 22 tries , about (81%) or near to it

Screen Record

so it not suported 100%

Ref :

1st screen record code

//Copyright (C) 2019 Potix Corporation. All Rights Reserved.
//History: Tue Apr 24 09:29 CST 2019
// Author: Jerry Chen

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll To Index Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Scroll To Index Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  static const maxCount = 100;
  final random = math.Random();
  final scrollDirection = Axis.vertical;

  AutoScrollController controller;
  List<List<int>> randomList;

  @override
  void initState() {
    super.initState();
    controller = AutoScrollController(
      viewportBoundaryGetter: () => Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
      axis: scrollDirection
    );
    randomList = List.generate(maxCount, (index) => <int>[index, (1000 * random.nextDouble()).toInt()]);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView(
        scrollDirection: scrollDirection,
        controller: controller,
        children: randomList.map<Widget>((data) {
          return Padding(
            padding: EdgeInsets.all(8),
            child: _getRow(data[0], math.max(data[1].toDouble(), 50.0)),
          );
        }).toList(),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToIndex,
        tooltip: 'Increment',
        child: Text(counter.toString()),
      ),
    );
  }

  int counter = -1;
  Future _scrollToIndex() async {
    setState(() {
      counter++;

      if (counter >= maxCount)
        counter = 0;
    });

    await controller.scrollToIndex(counter, preferPosition: AutoScrollPosition.begin);
    controller.highlight(counter);
  }

  Widget _getRow(int index, double height) {
    return _wrapScrollTag(
      index: index,
      child: Container(
        padding: EdgeInsets.all(8),
        alignment: Alignment.topCenter,
        height: height,
        decoration: BoxDecoration(
          border: Border.all(
            color: Colors.lightBlue,
            width: 4
          ),
          borderRadius: BorderRadius.circular(12)
        ),
        child: Text('index: $index, height: $height'),
      )
    );
  }

  Widget _wrapScrollTag({int index, Widget child})
  => AutoScrollTag(
    key: ValueKey(index),
    controller: controller,
    index: index,
    child: child,
    highlightColor: Colors.black.withOpacity(0.1),
  );
}

2nd screen record code :

//Copyright (C) 2019 Potix Corporation. All Rights Reserved.
//History: Tue Apr 24 09:29 CST 2019
// Author: Jerry Chen

import 'dart:math' as math;

import 'package:flutter/material.dart';
import 'package:scroll_to_index/scroll_to_index.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Scroll To Index Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Scroll To Index Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final scrollDirection = Axis.vertical;
  var rnd = math.Random();
  int min = 50;
  int max = 200;
  AutoScrollController controller;
  @override
  void initState() {
    super.initState();
    controller = AutoScrollController(
        viewportBoundaryGetter: () =>
            Rect.fromLTRB(0, 0, 0, MediaQuery.of(context).padding.bottom),
        axis: scrollDirection);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: ListView.builder(
        scrollDirection: scrollDirection,
        controller: controller,
        itemBuilder: (context, i) => Padding(
          padding: EdgeInsets.all(8),
          child: _getRow(i, (min + rnd.nextInt(max - min)).toDouble()),
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _scrollToIndex,
        tooltip: 'Increment',
        child: Text(counter.toString()),
      ),
    );
  }

  int counter = -1;
  Future _scrollToIndex() async {
    setState(() {
      counter++;
    });

    await controller.scrollToIndex(counter,
        preferPosition: AutoScrollPosition.begin);
    controller.highlight(counter);
  }

  Widget _getRow(int index, double height) {
    return _wrapScrollTag(
        index: index,
        child: Container(
          padding: EdgeInsets.all(8),
          alignment: Alignment.topCenter,
          height: height,
          decoration: BoxDecoration(
              border: Border.all(color: Colors.lightBlue, width: 4),
              borderRadius: BorderRadius.circular(12)),
          child: Text('index: $index, height: $height'),
        ));
  }

  Widget _wrapScrollTag({int index, Widget child}) => AutoScrollTag(
        key: ValueKey(index),
        controller: controller,
        index: index,
        child: child,
        highlightColor: Colors.black.withOpacity(0.1),
      );
}

这篇关于颤振-如何以编程方式自动滚动到具有动态高度的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆