在更新同一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
}
),
],
),
);
}
}
答案 0 :(得分:0)
假设PuzzleSolver().solve()
方法是Future
,则可以执行以下操作:
void _solve() async{
setState(() {
_isSolving = true;
});
_solution = await PuzzleSolver().solve(); // waits for the future to finish
setState(() {
_isSolving = false;
});