gpt4 book ai didi

android-studio - 如何将 json 数据传递给 flutter widget

转载 作者:IT王子 更新时间:2023-10-29 07:13:21 26 4
gpt4 key购买 nike

我是 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 类(class))时它工作正常:

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.
);
}
}

最佳答案

由于您的文本小部件被定义为常量,因此小部件的标签或属性也应该是常量,因为您的数据是动态的,在编译时本身不是常量,您将看到错误。

Const Widget 必须从可以在编译时计算的数据创建。 const 对象无权访问您需要在运行时计算的任何内容。 1 + 2 是一个有效的 const 表达式,但 new DateTime.now() 不是。

From : More about Const, Static, Final

关于android-studio - 如何将 json 数据传递给 flutter widget,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52703182/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com