我认为问题在于代码中的URL拼写错误。然而,完整的例子如下:
import 'dart:async';
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(new MaterialApp(
home: MainScreen(),
));
}
class MainScreen extends StatelessWidget {
@override
Widget build(BuildContext context) {
return FutureBuilder(
future: getJson(),
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.hasData) {
return Container(
child: new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
centerTitle: true,
backgroundColor: Colors.redAccent,
),
body: new Column(
children: <Widget>[new Text(snapshot.data[0]['id'].toString())],
),
),
);
} else if(snapshot.hasError) {
return Container(
child: new Scaffold(
appBar: new AppBar(
title: new Text('Demo'),
centerTitle: true,
backgroundColor: Colors.redAccent,
),
body: new Column(
children: <Widget>[new Text(snapshot.error.toString())],
),
),
);
}else{
return Scaffold(
body: Container(
child: Center(child: CircularProgressIndicator()),
),
);
}
});
}
}
Future<List<dynamic>> getJson() async {
try {
String apiUrl = 'http://bannersmonster.com/demo.json';
http.Response response = await http.get(apiUrl);
return json.decode(response.body);
} catch (e) {
throw Exception('Problem with data'+e.toString());
}
}
注: