任何人都可以解释以下内容: 我在Flutter中创建了10个小部件,并将它们放在“列表”小部件中。调用小部件的dispose方法时,它是关于它的控制台日志。每个小部件在创建时都会分配一个编号。
情况如下:创建了10个小部件,一切都很好,然后每隔5秒便开始删除它们。 编号为1、2、3等的小部件将从列表中删除,但始终将编号为10(最后一个)的小部件称为dispose。
这是日志:
I/flutter (10173): created 1
I/flutter (10173): created 2
I/flutter (10173): created 3
I/flutter (10173): created 4
I/flutter (10173): created 5
I/flutter (10173): created 6
I/flutter (10173): created 7
I/flutter (10173): created 8
I/flutter (10173): created 9
I/flutter (10173): created 10
I/flutter (10173): removed 1
I/flutter (10173): disposed 10
I/flutter (10173): removed 2
I/flutter (10173): disposed 10
I/flutter (10173): removed 3
I/flutter (10173): disposed 10
I/flutter (10173): removed 4
I/flutter (10173): disposed 10
I/flutter (10173): removed 5
I/flutter (10173): disposed 10
I/flutter (10173): removed 6
I/flutter (10173): disposed 10
I/flutter (10173): removed 7
I/flutter (10173): disposed 10
I/flutter (10173): removed 8
I/flutter (10173): disposed 10
I/flutter (10173): removed 9
I/flutter (10173): disposed 10
I/flutter (10173): removed 10
I/flutter (10173): disposed 10
GreenContainer.dart:
import 'package:flutter/material.dart';
class GreenContainer extends StatefulWidget {
String requestId;
Future timer;
GreenContainer({this.requestId, this.timer});
@override
_GreenContainerState createState() => new _GreenContainerState();
}
class _GreenContainerState extends State<GreenContainer> {
_GreenContainerState() : super();
@override
void dispose() async {
print('disposed ${widget.requestId}');
super.dispose();
}
@override
void initState() {
print('created ${widget.requestId}');
super.initState();
}
@override
Widget build(BuildContext context) {
return Padding(
padding: EdgeInsets.only(top: 10.0),
child: Container(
height: 100.0,
color: Colors.green,
),
);
}
}
main.dart:
import 'package:flutter/material.dart';
import 'package:flutter_app_test/Classs.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List<GreenContainer> list = [];
@override
void initState() {
print('inited');
for (int i = 1; i <= 10; i++){
list.add(
new GreenContainer(requestId: i.toString(), timer: new Future.delayed(new Duration(milliseconds: 5000 * i ), (){
print('removed ' + i.toString());
setState(() {
list.removeAt(i);
print(list);
});
})
)
);
}
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: SingleChildScrollView(
child: Column(
children: list,
),
)
);
}
}
似乎是一个问题。请帮助。