这是将要解码的json
{
"id": "RG-01-190919-00000001",
"note": "",
"items": null,
"outlet": {
"operational_times": [{
"day_name": "Monday",
"is_holiday": false,
"operational_times": [{
"time_to_open": "07.00",
"time_to_close": "17.00"
}]
}]
}
}
json来自我通过Web服务调用的数据库,并与诸如此类的未来构建器一起显示
FutureBuilder(
future: Http.getData(endpoint: "wsm/wsm_get_invoice_by_id_outlet_json.json",
data: {"invoice_id": widget.idinvoice}),
builder: (context, snapshot) {
if (snapshot.hasData) {
if (snapshot.data.toString() != "[]" &&
snapshot.data != null) {
var item = snapshot.data;
}
}
}
)
但是当我像day_name
一样在operational_times
内部呼叫Text(item["outlet"]["operational_times"]["day_name"])
时。
出现错误
类型'String'不是'索引'的类型'int'的子类型
如果day_name
位于数组中并包装在对象中,那么如何显示
答案 0 :(得分:0)
如果您的json看起来像这样,并在getData()中,则使用json.decode(jsonString)返回动态值
您可以在
{
"id": "RG-01-190919-00000001",
"note": "",
"items": null,
"outlet": {
"operational_times": [{
"day_name": "Monday",
"is_holiday": false,
"operational_times": [{
"time_to_open": "07.00",
"time_to_close": "17.00"
}]
},
{
"day_name": "Tuesday",
"is_holiday": false,
"operational_times": [{
"time_to_open": "07.00",
"time_to_close": "17.00"
}]
}]
}
}
代码段
FutureBuilder<dynamic>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data["outlet"]["operational_times"].length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data["outlet"]["operational_times"][index]["day_name"]),
);
});
}
}
})
工作演示
完整代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: 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 simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
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() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
Future<dynamic> getData() async {
String jsonString = '''
{
"id": "RG-01-190919-00000001",
"note": "",
"items": null,
"outlet": {
"operational_times": [{
"day_name": "Monday",
"is_holiday": false,
"operational_times": [{
"time_to_open": "07.00",
"time_to_close": "17.00"
}]
},
{
"day_name": "Tuesday",
"is_holiday": false,
"operational_times": [{
"time_to_open": "07.00",
"time_to_close": "17.00"
}]
}]
}
}
''';
return json.decode(jsonString);
/*final response = await http.get('http://api.open-notify.org/astros');
if (response.statusCode == 200) {
// If the call to the server was successful, parse the JSON.
return json.decode(response.body);
} else {
// If that call was not successful, throw an error.
throw Exception('Failed to load post');
}*/
}
@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 Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: FutureBuilder<dynamic>(
future: getData(),
builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
switch (snapshot.connectionState) {
case ConnectionState.none:
return Text('Input a URL to start');
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
case ConnectionState.active:
return Text('');
case ConnectionState.done:
if (snapshot.hasError) {
return Text(
'${snapshot.error}',
style: TextStyle(color: Colors.red),
);
} else {
return ListView.builder(
itemCount: snapshot.data["outlet"]["operational_times"].length,
itemBuilder: (context, index) {
return ListTile(
title: Text(snapshot.data["outlet"]["operational_times"][index]["day_name"]),
);
});
}
}
}));
}
}