我在flutter中有一个正在初始化某个类对象的类。我想调用该类,对象将被初始化,并且我想在调用者类中访问该对象。
下面是我的代码
import 'package:flutter/material.dart';
@immutable
class CardviewListItem {
//final FlatButton icon;
final IconData icon;
final String title;
final String amount;
const CardviewListItem({
@required this.icon,
@required this.title,
@required this.amount,
});
}
class SomeOtherClass {
final summaryListItems = <CardviewListItem>[
CardviewListItem(
title: 'Total Income',
amount:'4434.65',
icon: makeIconWithCircle(Icons.attach_money) // call function to create an icon with a circle in the background.
),
];
static Widget makeIconWithCircle(IconData iconData) { // function takes in the icon you want to create with a green background
final circle = Container(
height: 25.0,
width: 25.0,
decoration: BoxDecoration(
color: Colors.green,
shape: BoxShape.circle
),
);
final icon = Icon(
iconData, // iconData paramater is used here
color: Colors.white,
size: 18,
);
final iconWithCircle = Stack(
alignment: Alignment.center,
children: <Widget>[
circle,
icon
],
);
return iconWithCircle;
}
}
我想调用SomeOtherClass并获得对summaryListItems对象的访问权限
这是我的呼叫者班级
import 'package:flutter/material.dart';
import 'package:finsec/widget/cardview_widget.dart';
import 'package:finsec/utils/strings.dart';
import 'package:finsec/utils/dimens.dart';
import 'package:finsec/utils/colors.dart';
import 'package:finsec/data/cardview_list_item.dart';
void main() {
runApp(new HomeScreen());
}
class HomeScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: new Stack(
children: <Widget>[
new Container(
height: margin_200dp,
color: colorPrimary,
),
new Container( //container to overlay on top of blue container
alignment: Alignment.topCenter,
padding: new EdgeInsets.only(top: margin_0dp, right: margin_8dp, left: margin_8dp, bottom: margin_5dp),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(
zeroAmount,
style: TextStyle(color: white, fontSize: 40.0, fontWeight: FontWeight.bold)
),
Text(
currentBalance, style: TextStyle(color: white, fontSize: 20.0, fontWeight: FontWeight.bold)
),
cardView(
header: summaryCard,
elevation: margin_4dp,
height: margin_220dp,
padding: margin_15dp,
listItems: <<I WANT TO ACCESS summaryListItems HERE>>
),
//cardView(context)
],
),
)
],
),
);
}
}
我希望能够调用SomeOtherClass并访问调用者类中的summaryListItems。
参见上面的代码行listItems:<>
答案 0 :(得分:0)
您只需要在HomeScreen中获取SomeOtherClass的实例,这取决于您要如何对其建模,某些类需要在屏幕上创建实例并将其注入到屏幕上,或者只是让屏幕创建它。最简单的方法是在屏幕上创建实例,基本上是:
class HomeScreen extends StatelessWidget {
SomeOtherClass someotherClass = SomeOtherClass();
然后在列表上只需使用
cardView(
header: summaryCard,
elevation: margin_4dp,
height: margin_220dp,
padding: margin_15dp,
listItems: someotherClass.summaryListItems,
),
希望有帮助,