我是Flutter和Dart的新手。我有一些基于api json的数据,这些数据的变量称为data
。我已经从flutter官方文档中获取了此示例代码,并且希望能够使用data
变量并替换字符串文本,如下所示:
return new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: const Icon(Icons.album),
title: const Text(data[index]['name']),
subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
new ButtonTheme.bar( // make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('BUY TICKETS'),
onPressed: () { /* ... */ },
),
new FlatButton(
child: const Text('LISTEN'),
onPressed: () { /* ... */ },
),
],
),
),
],
),
);
但是我在第title: const Text(data[index]['name']),
行遇到错误,并且错误显示Argument of type constant creation must be constant expression
。该错误来自Android Studio本身(版本3.2)
但是当我使用这段代码(取自youtube课程)时,它工作正常:
return new Container(
child: new Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[
new Card(
child: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Container(
child: Text(data[index]['name'],
style: TextStyle(
fontSize: 16.0, color: Colors.black54))),
)),
new Card(
child: new Padding(
padding: const EdgeInsets.all(16.0),
child: new Container(
child: Text(data[index]['description'],
style: TextStyle(
fontSize: 16.0, color: Colors.redAccent)),
)),
)
],
),
);
如何使用第一个代码示例而不会出现任何错误?谢谢!
更新:这是完整的代码
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() => runApp(new MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'Flutter Demo',
theme: new ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or press Run > Flutter Hot Reload in IntelliJ). Notice that the
// counter didn't reset back to zero; the application is not restarted.
primarySwatch: Colors.green,
),
home: new MyHomePage(title: 'Flutter App'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => new _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
List data;
Future<String> getData() async {
http.Response response = await http.get(
Uri.encodeFull('https://dummyapicall.api'),
headers: {
"Accept": "application/json",
}
);
this.setState(() {
data = json.decode(response.body);
});
return 'Success!';
}
@override
void initState() {
super.initState();
this.getData();
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new ListView.builder(
itemCount: data == null ? 0 : data.length,
itemBuilder: (BuildContext context, int index) {
// return new Container(
// child: new Column(
// crossAxisAlignment: CrossAxisAlignment.stretch,
// children: <Widget>[
// new Card(
// child: new Padding(
// padding: const EdgeInsets.all(16.0),
// child: new Container(
// child: Text(data[index]['name'],
// style: TextStyle(
// fontSize: 16.0, color: Colors.black54))),
// )),
// new Card(
// child: new Padding(
// padding: const EdgeInsets.all(16.0),
// child: new Container(
// child: Text(data[index]['description'],
// style: TextStyle(
// fontSize: 16.0, color: Colors.redAccent)),
// )),
// )
// ],
// ),
// );
return new Card(
child: new Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
const ListTile(
leading: const Icon(Icons.album),
title: const Text(data[index]['name']),
subtitle: const Text('Music by Julie Gable. Lyrics by Sidney Stein.'),
),
new ButtonTheme.bar( // make buttons use the appropriate styles for cards
child: new ButtonBar(
children: <Widget>[
new FlatButton(
child: const Text('BUY TICKETS'),
onPressed: () { /* ... */ },
),
new FlatButton(
child: const Text('LISTEN'),
onPressed: () { /* ... */ },
),
],
),
),
],
),
);
},
),
// floatingActionButton: new FloatingActionButton(
// onPressed: _incrementCounter,
// tooltip: 'Increment',
// child: new Icon(Icons.add),
// ), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
答案 0 :(得分:1)
只需在const
的两个位置都删除ListTile
关键字。
当您在“文本”小部件中包含变量(数据)时,它们就不能保持恒定。
children: <Widget>[
ListTile(
leading: const Icon(Icons.album),
title: Text(data[index]['name']),
subtitle: const Text(
'Music by Julie Gable. Lyrics by Sidney Stein.'),
),
.....
答案 1 :(得分:1)
由于您的“文本”窗口小部件定义为const,因此标签或窗口小部件的属性也应为const,因为在编译时数据是动态的而不是const,因此您会看到错误。
Const Widget必须由可在编译时计算出的数据创建。 const对象无权访问在运行时需要计算的任何内容。 1 + 2是有效的const表达式,但新的DateTime.now()不是。