【发布时间】:2019-12-30 22:29:39
【问题描述】:
在同一 setState() 中的一些先前变量已更新后,我需要在 setState() 中运行一个方法。目前它在更新页面之前等待方法完成。
(我是 Flutter 新手,编程能力不是很好)。
我尝试将 setState() 拆分为不同的:
// this method is called once the animation has finished
void _solve() {
setState(() {
_isSolving = true; // I need to update the display here
});
setState(() {
_solution = PuzzleSolver().solve(); // this takes some time and returns a map
});
setState(() {
_isSolving = false; // and I need to update the display again here
});
}
但这并没有帮助,因为我真的不知道这一切是如何运作的。
这是代码的精简版:
import 'package:flutter/material.dart';
import './puzzleSolver.dart';
class SomePage extends StatefulWidget {
@override
_SomePageState createState() => _SomePageState();
}
class _SomePageState extends State<SomePage> with TickerProviderStateMixin {
AnimationController animationController;
Map _solution = {};
bool _isSolving = false;
void initState() {
super.initState();
animationController = AnimationController(
vsync: this, duration: Duration(seconds: 5))
..addStatusListener(
(state) => (state == AnimationStatus.dismissed) ? _solve() : null); // run _solve() once the animation has finished
animationController.reverse();
}
// this method is called once the animation has finished
void _solve() {
setState(() {
_isSolving = true; // I need to update the display here
_solution = PuzzleSolver().solve(); // this takes some time and returns a map
_isSolving = false; // and I need to update the display here again
});
// at the moment it updates the display here
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Some Page'),
),
body: Column(
children: <Widget>[
(_isSolving == false && _solution.isEmpty)
? Text('hello world') // only show when it's not solving and there is no solution
: RaisedButton(
child: Text('show solution'),
onPressed: (_isSolving)
? null // disable the button when its solving
: () {}, // enable it when its solved
),
AnimatedBuilder(
animation: animationController,
builder: (BuildContext context, Widget child) {
return Container(); // this is where the animated widgets would be
}
),
],
),
);
}
}
【问题讨论】:
-
PuzzleSolver().solve()方法是否返回Future? -
您可以在
PuzzleSolver中使用 async,并为它使用await,然后使用setState
标签: flutter