在Flutter中制作循环动画

时间:2019-03-08 02:09:03

标签: animation dart flutter mobile-development flutter-animation

我正在尝试制作扑朔迷离的排序算法动画。到目前为止,我已经对算法进行了编码,并通过一次迭代而不是整个排序过程来设法获得了某种动画,但是您必须不断点击按钮来进行一次排序。我一直在努力寻找一种动画制作此过程的方法。这是我的代码:

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

List<double> rectHeights = new List<double>();
int n = 2;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Sorting',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

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

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  int _selectedIndex = 0;
  final _widgetOptions = [
    Text('Index 0: Sort'),
    Text('Index 1: Shuffle'),
  ];

  @override
  void initState() {
    super.initState();
    Random random = new Random();
    for (int i = 0; i < 35; i++) {
      double ranNum = random.nextDouble() * 600;
      rectHeights.add(ranNum);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Padding(
        padding: EdgeInsets.all(8.0),
        child: Center(
          child: Row(
            children: rectangles(),
          ),
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        iconSize: 50.0,
          items: <BottomNavigationBarItem>[
            BottomNavigationBarItem(icon: Icon(Icons.sort), title: Text('Sort', style: TextStyle(fontSize: 20.0),)),
            BottomNavigationBarItem(icon: Icon(Icons.shuffle), title: Text('Shuffle', style: TextStyle(fontSize: 20.0),)),
          ],
        currentIndex: _selectedIndex,
        fixedColor: Colors.blue,
        onTap: _onItemTapped,
      ),
    );
  }

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
    switch(_selectedIndex) {
      case 0:
          setState(() {
            insertSortOnce(rectHeights, 1);
          });
          break;
      case 1:
        setState(() {
          shuffle(rectHeights);
          n = 2;
        });

    }
  }
}


List<Widget> rectangles() {
  List<Widget> rects = new List<Widget>();
  for (double height in rectHeights) {
    var rect = Padding(
      padding: EdgeInsets.symmetric(horizontal: 1.0),
      child: Container(
        width: 8.0,
        height: height,
        decoration: BoxDecoration(
            shape: BoxShape.rectangle,
            color: Colors.blue
        ),
      ),
    );
    rects.add(rect);
  }
  return rects;
}

void insertSort(values, choice) {
  int i, j;
  double key, temp;
  for (i = 1; i < values.length; i++) {
    key = values[i];
    j = i - 1;
    switch (choice) {
      case 1:
        while (j >= 0 && key < values[j]) {
          temp = values[j];
          values[j] = values[j + 1];
          values[j + 1] = temp;
          j--;
        }
        break;
      case 2:
        while (j >= 0 && key > values[j]) {
          temp = values[j];
          values[j] = values[j + 1];
          values[j + 1] = temp;
          j--;
        }
        break;
    }
  }
}

void insertSortOnce(values, choice) {
  int i, j;
  double key, temp;
  for (i = 1; i < n; i++) {
    key = values[i];
    j = i - 1;
    switch (choice) {
      case 1:
        while (j >= 0 && key < values[j]) {
          temp = values[j];
          values[j] = values[j + 1];
          values[j + 1] = temp;
          j--;
        }
        break;
      case 2:
        while (j >= 0 && key > values[j]) {
          temp = values[j];
          values[j] = values[j + 1];
          values[j + 1] = temp;
          j--;
        }
        break;
    }
  }
  n++;
}

List shuffle(List items) {
  var random = new Random();

  // Go through all elements.
  for (var i = items.length - 1; i > 0; i--) {

    // Pick a pseudorandom number according to the list length
    var n = random.nextInt(i + 1);

    var temp = items[i];
    items[i] = items[n];
    items[n] = temp;
  }

  return items;
}

1 个答案:

答案 0 :(得分:0)

您可以短暂使用Future函数,例如(一秒钟)每秒之后调用insertSort(),直到rectHeights被排序为止。

  var _notSorted = true ;
  var _shiftNotPressed = true ;

  Future sortRectangles() async {
  while(_notSorted & _shiftPressed) { // You have to provide a condition to know when to stop
  await new Future.delayed(const Duration(seconds: 1), () {
      insertSortOnce(rectHeights, 1);
      }
    );
  }
} 

然后检查混洗:

    void _onItemTapped(int index) {
setState(() {
  _selectedIndex = index;
});
switch(_selectedIndex) {
  case 0:
      setState(() {
        insertSortOnce(rectHeights, 1);
      });
      break;
  case 1:
    _shiftNotPressed = false ; // This is what you should add
    setState(() {
      shuffle(rectHeights);
      n = 2;
    });

  }
}

然后排序完成:

   void insertSortOnce(values, choice) {
   _notSorted = false ; // if it didn't execute the loop it means sorted 
   int i, j;
   double key, temp;
   for (i = 1; i < n; i++) {
   key = values[i];
   j = i - 1;
   switch (choice) {
     case 1:
      while (j >= 0 && key < values[j]) {
       _notSorted = true ; //You should figure a more efficient way to do this
       temp = values[j];
       values[j] = values[j + 1];
       values[j + 1] = temp;
       j--;
      }
     break;
    case 2:
    while (j >= 0 && key > values[j]) {
      temp = values[j];
      values[j] = values[j + 1];
      values[j + 1] = temp;
      j--;
    }
    break;
   }
 }
 n++;
}

此外,您还应在条件中包括是否按下了Shift键并相应地终止。