it营大地专栏

Flutter ReorderableListView 可拖拽的列表

发布于 3 个月前 作者 sinazl 273 次浏览 来自 分享

Flutter ReorderableListView 可拖拽的列表

import 'package:flutter/material.dart';
import 'dart:math' as math;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}

class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  List<String> items = List.generate(10, (int i) => '$i');
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ReorderableListView(
        onReorder: (int oldIndex, int newIndex) {
          print(oldIndex);
          print(newIndex);
          var element = items[oldIndex];
          if (newIndex >= items.length) newIndex = items.length - 1;
          setState(() {
            items.removeAt(oldIndex);
            items.insert(newIndex, element);
          });
        },
        children: <Widget>[
          for (String el in items)
            ListTile(
              key: ValueKey(el),
              title: Text('Item $el'),
            ),
        ],
      ),
    );
  }
}
回到顶部