Flutter 从api检索json的主体
我正试图从以下api返回报价部分: json如下所示: {u id:“9hIehvX23pvr”,“content:”没有魅力能与温柔相提并论 《心的力量》,《作者》:《简·奥斯汀》} 下面是连接到API的代码部分Flutter 从api检索json的主体,flutter,dart,Flutter,Dart,我正试图从以下api返回报价部分: json如下所示: {u id:“9hIehvX23pvr”,“content:”没有魅力能与温柔相提并论 《心的力量》,《作者》:《简·奥斯汀》} 下面是连接到API的代码部分 Future<String> _getQuote() async { final res = await http.get('https://api.quotable.io/random'); return json.decode(res.body); } Fu
Future<String> _getQuote() async {
final res = await http.get('https://api.quotable.io/random');
return json.decode(res.body);
}
Future\u getQuote()异步{
final res=等待http.get('https://api.quotable.io/random');
返回json.decode(res.body);
}
每当我运行应用程序时,我都会收到一个错误,告诉我它得到了一个空值。但我知道api是有效的
_FutureBuilderState(b8df9):I/flatter(5315):必须向文本小部件提供非空字符串。I/颤振(5315):
'package:flatter/src/widgets/text.dart':I/flatter(5315):失败
断言:第269行第10位:“数据!”空'
我只需要json的“内容”部分。我如何解析这一部分
谢谢 @SkyeBoniwell,没有收到api的任何响应。真的有用吗 截图:
您可以复制下面的粘贴运行完整代码
步骤1:将
添加到AndroidManifest
步骤2:使用以下类解析
Demo demoFromJson(String str) => Demo.fromJson(json.decode(str));
String demoToJson(Demo data) => json.encode(data.toJson());
class Demo {
String id;
String content;
String author;
Demo({
this.id,
this.content,
this.author,
});
factory Demo.fromJson(Map<String, dynamic> json) => Demo(
id: json["_id"],
content: json["content"],
author: json["author"],
);
Map<String, dynamic> toJson() => {
"_id": id,
"content": content,
"author": author,
};
}
Demo-demoFromJson(String-str)=>Demo.fromJson(json.decode(str));
字符串demojojson(Demo data)=>json.encode(data.toJson());
课堂演示{
字符串id;
字符串内容;
字符串作者;
演示({
这个身份证,
这个.内容,,
这位作者,
});
工厂Demo.fromJson(映射json)=>Demo(
id:json[“_id”],
内容:json[“内容”],
作者:json[“作者”],
);
映射到JSON()=>{
“_id”:id,
“内容”:内容,
“作者”:作者,
};
}
工作演示
完整工作代码
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:async';
import 'dart:convert';
Demo demoFromJson(String str) => Demo.fromJson(json.decode(str));
String demoToJson(Demo data) => json.encode(data.toJson());
class Demo {
String id;
String content;
String author;
Demo({
this.id,
this.content,
this.author,
});
factory Demo.fromJson(Map<String, dynamic> json) => Demo(
id: json["_id"],
content: json["content"],
author: json["author"],
);
Map<String, dynamic> toJson() => {
"_id": id,
"content": content,
"author": author,
};
}
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(
primarySwatch: Colors.blue,
),
home: FutureBuilderWidget(),
);
}
}
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.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}
String url = ' http://api.quotable.io/random';
///Method for GET Request
Future<Demo> getDemoResponse() async {
final response = await http.get('https://api.quotable.io/random');
print('response ${response}');
if (response.statusCode == 200) {
print('response body${response.body}');
return demoFromJson(response.body);
} else {
throw Exception('Failed to load ');
}
}
class FutureBuilderWidget extends StatefulWidget {
@override
_FutureBuilderWidgetState createState() => _FutureBuilderWidgetState();
}
class _FutureBuilderWidgetState extends State<FutureBuilderWidget> {
bool _isButtonClicked = false;
var _buttonIcon = Icons.cloud_download;
var _buttonText = "Fetch Data";
var _buttonColor = Colors.green;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Container(
child: Center(
child: Text(
'Future Builder Widget',
style: TextStyle(
fontSize: 20.0,
fontWeight: FontWeight.bold,
//fontFamily: Utils.ubuntuRegularFont
),
),
),
margin: EdgeInsets.only(right: 48),
),
),
body: Center(
child: FutureBuilder<Demo>(
///If future is null then API will not be called as soon as the screen
///loads. This can be used to make this Future Builder dependent
///on a button click.
future: _isButtonClicked ? getDemoResponse() : null,
builder: (context, snapshot) {
switch (snapshot.connectionState) {
///when the future is null
case ConnectionState.none:
return Text(
'Press the button to fetch data',
textAlign: TextAlign.center,
);
case ConnectionState.active:
///when data is being fetched
case ConnectionState.waiting:
return CircularProgressIndicator(
valueColor: AlwaysStoppedAnimation<Color>(Colors.blue));
case ConnectionState.done:
///task is complete with an error (eg. When you
///are offline)
if (snapshot.hasError)
return Text(
'Error:\n\n${snapshot.error}',
textAlign: TextAlign.center,
);
///task is complete with some data
return Text(
'Fetched Data:\n\n${snapshot.data.content}',
textAlign: TextAlign.center,
);
}
},
),
),
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat,
floatingActionButton: FloatingActionButton.extended(
backgroundColor: _buttonColor,
onPressed: () {
///Calling method to fetch data from the server
//getDemoResponse();
///You need to reset UI by calling setState.
setState(() {
_isButtonClicked == false
? _isButtonClicked = true
: _isButtonClicked = false;
if (!_isButtonClicked) {
_buttonIcon = Icons.cloud_download;
_buttonColor = Colors.green;
_buttonText = "Fetch Data";
} else {
_buttonIcon = Icons.replay;
_buttonColor = Colors.deepOrange;
_buttonText = "Reset";
}
});
},
icon: Icon(
_buttonIcon,
color: Colors.white,
),
label: Text(
_buttonText,
style: TextStyle(color: Colors.white),
),
),
);
}
}
导入“包装:颤振/材料.省道”;
将“package:http/http.dart”导入为http;
导入“dart:async”;
导入“dart:convert”;
Demo demoFromJson(String str)=>Demo.fromJson(json.decode(str));
字符串demojojson(Demo data)=>json.encode(data.toJson());
课堂演示{
字符串id;
字符串内容;
字符串作者;
演示({
这个身份证,
这个.内容,,
这位作者,
});
工厂Demo.fromJson(映射json)=>Demo(
id:json[“_id”],
内容:json[“内容”],
作者:json[“作者”],
);
映射到JSON()=>{
“_id”:id,
“内容”:内容,
“作者”:作者,
};
}
void main()=>runApp(MyApp());
类MyApp扩展了无状态小部件{
//此小部件是应用程序的根。
@凌驾
小部件构建(构建上下文){
返回材料PP(
标题:“颤振演示”,
主题:主题数据(
主样本:颜色。蓝色,
),
主页:FutureBuilderWidget(),
);
}
}
类MyHomePage扩展StatefulWidget{
MyHomePage({Key,this.title}):超级(Key:Key);
最后的字符串标题;
@凌驾
_MyHomePageState createState()=>\u MyHomePageState();
}
类_MyHomePageState扩展状态{
int _计数器=0;
void _incrementCounter(){
设置状态(){
_计数器++;
});
}
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:文本(widget.title),
),
正文:中(
子:列(
mainAxisAlignment:mainAxisAlignment.center,
儿童:[
正文(
“您已经按了这么多次按钮:”,
),
正文(
“$”计数器“,
样式:Theme.of(context).textTheme.display1,
),
],
),
),
浮动操作按钮:浮动操作按钮(
按下时:\ u递增计数器,
工具提示:“增量”,
子:图标(Icons.add),
),
);
}
}
字符串url='0http://api.quotable.io/random';
///获取请求的方法
未来的getDemoResponse()异步{
最终响应=等待http.get('https://api.quotable.io/random');
打印('response${response}');
如果(response.statusCode==200){
打印('response body${response.body}');
返回demoFromJson(response.body);
}否则{
抛出异常(“加载失败”);
}
}
类FutureBuilderWidget扩展StatefulWidget{
@凌驾
_FutureBuilderWidgetState createState()=>\u FutureBuilderWidgetState();
}
类\u FutureBuilderWidgetState扩展状态{
bool _isButtonClicked=false;
var\u buttonIcon=Icons.cloud\u下载;
var\u buttonText=“获取数据”;
var_buttonColor=Colors.green;
@凌驾
小部件构建(构建上下文){
返回脚手架(
appBar:appBar(
标题:集装箱(
儿童:中心(
子:文本(
“Future Builder Widget”,
样式:TextStyle(
字体大小:20.0,
fontWeight:fontWeight.bold,
//fontFamily:Utils.ubuntuRegularFont
),
),
),
页边距:仅限边集(右:48),
),
),
正文:中(
孩子:未来建设者(
///如果future为null,则屏幕显示后将不会立即调用API
///加载。这可用于使此未来生成器依赖
///按一下按钮。
future:\u isButtonClicked?getDemoResponse():null,
生成器:(上下文,快照){
交换机(快照.连接状态){
///当未来是空的
案例连接状态。无:
返回文本(
'按按钮获取数据',
textAlign:textAlign.center,
);
案例连接状态.active:
///在提取数据时
案例连接状态。正在等待:
返回循环预测器(
valueColor:AlwaysStoppedAnimation(Colors.blue));
案例连接状态。完成:
///任务完成时出现错误(例如,当您
///(正在脱机)
if(snapshot.hasError)
返回文本(