【发布时间】:2018-10-27 05:46:37
【问题描述】:
我想制作一个即将到来的任务类型的 UI,带有用于任务开始和停止的滑块按钮。这些按钮在水平滑动时呈现滑块动画。 我还想让任务在完成后从列表中消失。
但是,我遇到了一个有状态按钮列表的问题,我没有在列表中添加一个,但它仍然会继续显示,而是添加到列表中的按钮消失了。这是我的代码:
import 'dart:core';
import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
class MyApp extends StatefulWidget {
@override
State createState() => new MyAppState();
}
class MyAppState extends State<MyApp> {
int state = 0;
@override
Widget build(BuildContext context) {
var redButton = new IconButton(
icon: new Icon(Icons.send, color: Colors.red),
onPressed: null
);
var blueButton = new IconButton(
icon: new Icon(Icons.send, color: Colors.blue),
onPressed: null
);
var clicker = new IconButton(
icon: new Icon(Icons.refresh, color: Colors.green),
onPressed: () {
setState(() {
state = state + 1;
});
}
);
List<Widget> list = new List();
list.add(new Text('$state'));
list.add(clicker);
if (state < 1) {
list.add(new _Button(redButton));
} else {
print ('Not showing red button');
}
print ('Showing blue button');
list.add(new _Button(blueButton));
return new MaterialApp(
title: 'Slide animation',
home: new Scaffold(
appBar: new AppBar(
title: new Center(child: new Text('Flutter stateful widget list bug')),
),
body: new Column(
children: list,
),
),
);
}
}
// Includes animation and other stuff - stripped for now
class _Button extends StatefulWidget {
static int counter = 0;
final Widget button;
final int id = counter++;
_SlidableButtonState state;
_Button(this.button);
@override
State createState() {
state = new _SlidableButtonState(button);
print ('${id} -> $state');
return state;
}
}
class _SlidableButtonState extends State<_Button> {
final Widget button;
_SlidableButtonState(this.button);
@override
void dispose() {
super.dispose();
print ('$this: dispose');
}
@override
Widget build(BuildContext context) {
// Some rendering stuff will come here
return button;
}
}
点击答题器按钮时,我希望红色按钮消失,蓝色按钮显示。但是,红色按钮仍在显示,蓝色按钮消失。以下是显示蓝色按钮已关闭的日志:
Launching lib/examples/list_bug_flutter.dart on Android SDK built for x86 in debug mode...
Initializing gradle...
Resolving dependencies...
Running 'gradlew assembleDebug'...
Built build/app/outputs/apk/debug/app-debug.apk (31.4MB).
Installing build/app/outputs/apk/app.apk...
I/FlutterActivityDelegate(26592): onResume setting current activity to this
I/flutter (26592): Showing blue button
Syncing files to device Android SDK built for x86...
I/flutter (26592): 0 -> _SlidableButtonState#cfe2f(lifecycle state: created, no widget, not mounted)
I/flutter (26592): 1 -> _SlidableButtonState#2d165(lifecycle state: created, no widget, not mounted)
I/flutter (26592): Not showing red button
I/flutter (26592): Showing blue button
I/flutter (26592): _SlidableButtonState#2d165(lifecycle state: defunct): dispose
I/flutter (26592): Not showing red button
I/flutter (26592): Showing blue button
【问题讨论】:
-
我想我找到了问题所在。如果我在
_SlidableButtonState中引用widget.button,那么一切正常。我的猜测是颤振不鼓励将值从StatefulWidget传递到其State对象