flutter之滚动到列表指定item位置教程

main.dart文件中代码如下,引入ListPage的路径自己定义:

import 'package:flutter/material.dart';
import 'package:learn_flutter/scroll_to_position/ListPage.dart';

void main() {runApp(new MyApp());}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'flutter列表滚动到指定位置',
      theme: new ThemeData(
        primaryColor: const Color(0xff43a047),
        accentColor: const Color(0xffffcc00),
        primaryColorBrightness: Brightness.dark
      ),
      home: new ListPage(),
      debugShowCheckedModeBanner: false,
    );
  }
}

首先,ListPage文件基础内容如下:

import 'package:flutter/material.dart';

const double _ITEM_HEIGHT = 70.0;

class Item {
  final String displayName;
  const Item(this.displayName);
}
 
class ListPage extends StatefulWidget {
  ListPage({Key key}) : super(key: key);
 
  @override
  _ListPageState createState() => new _ListPageState();
}
 
class _ListPageState extends State {
 
  List _items;
 
  @override
  void initState() {
    super.initState();
 
    _items = new List();
    _items.add(new Item('詹姆斯'));
    _items.add(new Item('杜兰特'));
    _items.add(new Item('库里'));
    _items.add(new Item('哈登'));
    _items.add(new Item('威少'));
    _items.add(new Item('欧文'));
    _items.add(new Item('戴维斯'));
    _items.add(new Item('汤神'));
    _items.add(new Item('格林'));
    _items.add(new Item('恩比德'));
    _items.add(new Item('保罗'));
    _items.add(new Item('乔丹'));
    _items.add(new Item('莱昂纳德'));
    _items.add(new Item('塔图姆'));
    _items.add(new Item('利拉德'));
    _items.add(new Item('乐福'));
    _items.add(new Item('科比'));
  }
 
  @override
  Widget build(BuildContext context) {
    Widget buttonsWidget = new Container(
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceEvenly,
        children: [
          new FlatButton(
            textColor: Colors.blueGrey,
            color: Colors.white,
            child: new Text('杜兰特'),
            onPressed: _scrollToKd,
          ),
          new FlatButton(
            textColor: Colors.blueGrey,
            color: Colors.white,
            child: new Text('科比'),
            onPressed:_scrollToKobe ,
          ),
        ],
      ),
    );
 
    Widget itemsWidget =
      new ListView(
          scrollDirection: Axis.vertical,
          shrinkWrap: true,
          children: _items.map((Item item) {
            return _singleItemDisplay(item);
          }).toList());
 
    return new Scaffold(
      appBar: new AppBar(
        title: new Text("flutter之滚动到列表指定item位置教程"),
      ),
      body: new Padding(
        padding: new EdgeInsets.symmetric(vertical: 0.0, horizontal: 4.0),
        child: new Column(children: [
          buttonsWidget,
          new Expanded(
            child:
            itemsWidget,),
        ],
        ),
      ),
    );
  }
 
  Widget _singleItemDisplay(Item item) {
    return new Container(
      height: _ITEM_HEIGHT,
      child: new Container (
        padding: const EdgeInsets.all(2.0),
        color: new Color(0x33000000),
        child: new Text(item.displayName),
      ),
    );
  }
 
  void _scrollToKd() {
    // TODO
  }
 
  void _scrollToKobe() {
    // TODO
  }
}

现在可以运行代码看看,可以看到上面是两个按钮,下面为内容列表

接下来实现滚动功能:
1、首先添加ScrollController:

 @override
  void initState() {
    super.initState();
//此处为新添加代码------start
    _scrollController = new ScrollController();
//此处为新添加代码------end
    _items = new List();
    _items.add(new Item('詹姆斯'));
    _items.add(new Item('杜兰特'));
    _items.add(new Item('库里'));
    _items.add(new Item('哈登'));
    _items.add(new Item('威少'));
    _items.add(new Item('欧文'));
    _items.add(new Item('戴维斯'));
    _items.add(new Item('汤神'));
    _items.add(new Item('格林'));
    _items.add(new Item('恩比德'));
    _items.add(new Item('保罗'));
    _items.add(new Item('乔丹'));
    _items.add(new Item('莱昂纳德'));
    _items.add(new Item('塔图姆'));
    _items.add(new Item('利拉德'));
    _items.add(new Item('乐福'));
    _items.add(new Item('科比'));
  }

2、itemsWidget中也要添加ScrollController:

 Widget itemsWidget = new ListView(
        scrollDirection: Axis.vertical,
//此处为新添加代码------start
        controller: _scrollController,
//此处为新添加代码------end
        shrinkWrap: true,
        children: _items.map((Item item) {
          return _singleItemDisplay(item);
        }).toList());

3、改造Item类

class Item {
  final String displayName;
//此处为新添加代码------start
  bool selected;
  Item(this.displayName, this.selected);
//此处为新添加代码------end
}

4、更新初始化数据:

 _items.add(new Item('詹姆斯', false));
    _items.add(new Item('杜兰特', false));
    _items.add(new Item('库里', false));
    _items.add(new Item('哈登', false));
    _items.add(new Item('威少', false));
    _items.add(new Item('欧文', false));
    _items.add(new Item('戴维斯', false));
    _items.add(new Item('汤神', false));
    _items.add(new Item('格林', false));
    _items.add(new Item('恩比德', false));
    _items.add(new Item('保罗', false));
    _items.add(new Item('乔丹', false));
    _items.add(new Item('莱昂纳德', false));
    _items.add(new Item('塔图姆', false));
    _items.add(new Item('利拉德', false));
    _items.add(new Item('乐福', false));
    _items.add(new Item('科比', false));

5、添加滚动到指定item的关键代码:

//此处为新添加代码------start
for (int i = 0; i < _items.length; i++) {
      if (_items.elementAt(i).selected) {
        _scrollController.animateTo(i * _ITEM_HEIGHT,
            duration: new Duration(seconds: 2), curve: Curves.ease);
      }
    }
//此处为新添加代码------end
    return new Scaffold()...

6、实现头部两个按钮的点击

 void _scrollToKd() {
    setState(() {
      for (var item in _items) {
        if (item.displayName == '杜兰特') {
          item.selected = true;
        } else {
          item.selected = false;
        }
      }
    });
  }

  void _scrollToKobe() {
    setState(() {
      for (var item in _items) {
        if (item.displayName == '科比') {
          item.selected = true;
        } else {
          item.selected = false;
        }
      }
    });
  }

完毕~

你可能感兴趣的:(flutter之滚动到列表指定item位置教程)