如果我有
Class TestModel {
String property1;
String property2;
bool property3;
}
class PageModel {
List<TestModel> information = [all the data for all 3 properties];
}
我想在开始(索引0)的列表信息中添加一个新项(我们称其为newItem),我该怎么做?我知道List.add可用于在List的开头添加项目,但是由于List信息是一个类的列表,因此我不确定在这种情况下我该怎么做。
在将newItem添加到信息中之前,是否需要使newItem成为TestModel类的变量?有没有一种方法可以分别处理每个属性(例如,类似List.add.property1 =“ String”,List.add.property2 =“ String”,List.add.property3 = true)
答案 0 :(得分:0)
您可以在下面复制粘贴运行完整代码
您可以使用constructor
并直接使用property
初始化
代码段
class TestModel {
String property1;
String property2;
bool property3;
TestModel({this.property1, this.property2, this.property3});
}
class PageModel {
List<TestModel> information = [
TestModel(property1: "1", property2: "2", property3: false),
TestModel(property1: "3", property2: "4", property3: true)
];
}
输出
I/flutter ( 7558): 1 2 false
I/flutter ( 7558): 3 4 true
完整代码
import 'package:flutter/material.dart';
class TestModel {
String property1;
String property2;
bool property3;
TestModel({this.property1, this.property2, this.property3});
}
class PageModel {
List<TestModel> information = [
TestModel(property1: "1", property2: "2", property3: false),
TestModel(property1: "3", property2: "4", property3: true)
];
}
void main() {
PageModel().information.forEach((element) => print(
" ${element.property1} ${element.property2} ${element.property3.toString()}"));
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
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> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}