这是我的main.dart文件和map.dart文件的代码 . 这里我试图通过点击map.dart文件中的“从 Map 中删除元素”按钮从Map <>联系人中删除一些键后,从main.dart文件中的map.dart文件获取Map <>联系人的长度 . 我从main.dart文件中的map.dart创建了MyMap类的对象,以获取Map的数据 . 但是我得到的mapLength的初始值是0.但我希望输出应该是Map <>联系人的长度,方法是点击main.dart中的凸起按钮“获取 Map 长度” .
main.dart
import 'package:flutter/material.dart';
import 'package:passing_length/map.dart';
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
primarySwatch: Colors.blue,
),
home: new MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State {
var mapPage = new MyMap();
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Padding(
padding: new EdgeInsets.all(20.00),
child: new RaisedButton(
onPressed: () {
print(mapPage.mapLength());
},
child: new Text("Get length of map"),
),
),
new Padding(
padding: new EdgeInsets.all(20.00),
child: new RaisedButton(
onPressed: () {
Navigator.push(
context,
new MaterialPageRoute(builder: (context) => new MyMap()),
);
},
child: new Text("Goto new Page"),
),
),
],
)));
}
}
map.dart
class MyMap extends StatefulWidget {
@override
_MyMapState createState() => new _MyMapState();
int mapLength() {
return new _MyMapState().mapLength;
}
}
class _MyMapState extends State {
Map contact = {
"AAAA": 1111,
"BBBB": 2222,
"CCCC": 3333,
"DDDD": 4444,
"EEEE": 5555,
"FFFF": 6666,
"GGGG": 7777,
};
int mapLength = 0;
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: "My Map",
home: new Scaffold(
appBar: new AppBar(title: new Text("My Map")),
body: new Center(
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
new Padding(
padding: new EdgeInsets.all(20.00),
child: new RaisedButton(
onPressed: () {
contact.remove(contact.keys.elementAt(contact.length - 1));
mapLength = contact.length;
print(mapLength);
},
child: new Text("Remove element from map"),
),
),
new Padding(
padding: new EdgeInsets.all(20.00),
child: new RaisedButton(
onPressed: () {
Navigator.pop(context);
},
child: new Text("Go Back"),
),
),
],
))),
);
}
}