[英]Fetch data from web api in flutter
I'm new to Flutter, and I want to insert the data retrieved by an API into string variables for use in another function.我是 Flutter 的新手,我想将 API 检索到的数据插入到字符串变量中,以便在另一个 function 中使用。 Thanks for your help
谢谢你的帮助
my code is:------------我的代码是:------------
import 'dart:convert' as convert;
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main(){
var infos;
getData() async{
String myUrl="https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
var req = await http.get(myUrl);
infos = convert.jsonDecode(req.body);
print(infos);
return infos;
}
getData();
// I want to Fetch data here in string variables
runApp(new MaterialApp(
title:'Fetch Data',
home: new Scaffold(
appBar: AppBar(
title: new Text('hello'),
backgroundColor: Colors.amber,
),
body: new Center(
child: new Text('test'),
),
),
));
}
You should use stateful widget to do it.你应该使用有状态的小部件来做到这一点。
Following code may help you more.以下代码可能会对您有所帮助。
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() {
runApp(
new MaterialApp(
title: 'Fetch Data',
home: Home(),
),
);
}
class Home extends StatefulWidget {
@override
_HomeState createState() => _HomeState();
}
class _HomeState extends State<Home> {
@override
void initState() {
super.initState();
getData().then((value) {
setState(() {
infos = value;
});
});
}
var infos;
getData() async {
String myUrl = "https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
var req = await http.get(myUrl);
infos = json.decode(req.body);
print(infos['name']);
return infos['name'];
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: AppBar(
title: new Text('hello'),
backgroundColor: Colors.amber,
),
body: new Center(
child: infos == null ? new Text('test') : Text(infos),
),
);
}
}
This would work perfectly, check it out:这将完美地工作,检查一下:
class Person {
final String name;
final String education;
final String skill;
Person({this.name, this.education, this.skill});
factory Person.fromJson(Map<String, dynamic> json) {
return Person(
name: json['name'],
education: json['education'],
skill: json['skill'],
);
}
}
class Fetch extends StatefulWidget {
@override
_FetchState createState() => _FetchState();
}
class _FetchState extends State<Fetch> {
Future<Person> fetchPerson;
Future<Person> getData() async {
String myUrl = "https://api.jsonbin.io/b/5e1219328d761771cc8b9394";
var response = await http.get(myUrl);
Map<String, dynamic> responseJson = convert.jsonDecode(response.body);
return Person.fromJson(responseJson);
}
@override
void initState() {
fetchPerson = getData();
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: new Text('hello'),
backgroundColor: Colors.amber,
),
body: FutureBuilder(
future: fetchPerson,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text(
'Name is: ${snapshot.data.name}',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
Text(
'Education is: ${snapshot.data.education}',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
Text(
'Skill is: ${snapshot.data.skill}',
textAlign: TextAlign.start,
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.w500,
),
),
],
),
);
} else if (snapshot.hasError) {
Text(
snapshot.error.toString(),
);
}
return Center(
child: CircularProgressIndicator(),
);
},
),
);
}
}
Fetch From API取自 API
import 'package:flutter/material.dart';
import 'package:flutter/semantics.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MaterialApp(home: Homepage()));
class Homepage extends StatefulWidget {
@override
_Homepagestate createState() => _Homepagestate();
}
class _Homepagestate extends State<Homepage> {
String Stringrespon;
List Listresponse;
Map Mapresponse;
List Listfacts;
Future fetchData() async {
http.Response response;
response = await http
.get('http://example.com');
if (response.statusCode == 200) {
setState(() {
Mapresponse = jsonDecode(response.body);
Listfacts = Mapresponse['Data'];
});
}
}
@override
void initState() {
fetchData();
// TODO: implement initState
super.initState();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Fetch data'),
backgroundColor: Colors.blue,
),
body: Mapresponse == null
? Container()
: SingleChildScrollView(
child: Column(
children: <Widget>[
// Text(
// Mapresponse['category'].toString(),
// style: TextStyle(fontSize: 30),
// ),
ListView.builder(
shrinkWrap: true,
physics: NeverScrollableScrollPhysics(),
itemBuilder: (context, index) {
return Container(
margin: EdgeInsets.all(10),
child: Column(
children: <Widget>[
//Image.network(Listfacts[index]['image_url']),
Text(
Listfacts[index]['LeaveTypeName'].toString(),
style: TextStyle(
fontSize: 24, fontWeight: FontWeight.bold),
),
Text(
Listfacts[index]['CreatedDate'].toString(),
style: TextStyle(fontSize: 15),
),
],
),
);
},
itemCount: Listfacts == null ? 0 : Listfacts.length,
)
],
),
),
);
}
}
Upload to Api上传到Api
import 'package:flutter/material.dart';
import 'SignUp.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
class Home extends StatefulWidget {
final String username;
Home({
Key key,
@required this.username,
}) : super(key: key);
@override
_Login createState() => _Login();
}
class _Login extends State<Home> {
Future upData(String reqDate, String fromdate, String todate,
String description, int fdays, int hdays, int typeleave) async {
var body = json.encode({
"EmployeeId": 19,
"LeaveTypeId": typeleave,
"RequestDate": reqDate,
"NoofFullDay": fdays,
"NoofHalfDay": hdays,
"Datefrom": fromdate,
"Dateto": todate,
"Description": description,
"Status": 1,
"CreatedBy": 20,
"UpdatedBy": null,
"CreatedDate": reqDate,
"UpdatedDate": null,
"IsDelete": false,
"IsActive": true,
});
http.Response response;
response = await http.post(
"http://example.com/save",
body: body,
headers: {'Content-type': 'application/json'});
}
//call updata
@override
Widget build(BuildContext context) {
return MaterialApp(
title: "Smple Login",
home: Scaffold(
resizeToAvoidBottomPadding: false,
body: Center(
child: Container(
child: RaisedButton(onPressed: () {
upData(
reqDateController.text,
fromdateController.text,
todateController.text,
descriptionController.text,
int.parse(fdaysController.text),
int.parse(hdaysController.text),
int.parse(_myState),
);
}),
),
),
),
);
}
}
Fetch With Parameter带参数获取
Future fetchData() async {
var body =
json.encode({"IsActive": true, "IsDelete": false, "CompanyId": 18});
http.Response response;
response = await http.post("http://example.com",
body: body, headers: {'Content-type': 'application/json'});
if (response.statusCode == 200) {
setState(() {
mapresponse = jsonDecode(response.body);
listfacts = mapresponse['Data'];
});
}
}
//Access listfacts[index]['Data']), //访问listfacts[index]['Data']),
class LoginModel {
String mobile;
int cacheEmpId;
int cacheCompId;
String loginOTP;
String oTPExpiredTime;
String role;
LoginModel({
this.mobile,
this.cacheEmpId,
this.cacheCompId,
this.loginOTP,
this.oTPExpiredTime,
this.role
});
LoginModel.fromJson(Map<String, dynamic> json) {
mobile = json['Mobile'] ?? "";
cacheEmpId=json['EmployeeId']??"";
cacheCompId=json['CompanyId']??"";
loginOTP = json['LoginOTP'] ?? "";
oTPExpiredTime = json['OTPExpiredTime'] ?? "";
role=json['ODRole']??"";
}
}
// here is the model
import 'package:http/http.dart' as http;
import 'package:officediaryapp/Models/LoginModel.dart';
import 'dart:convert';
import 'package:officediaryapp/Utils/Api_Utils.dart';
class LoginService {
bool error = false;
bool loading = true;
var login;
bool loginDetailserror = false;
bool logindtailsloading = true;
Future<LoginModel> getLogin(dynamic input, String mob) async {
try {
loginDetailserror = false;
http.Response response = await http.get(ApiUtils.loginApi + mob,
headers: {'Content-type': 'application/json'});
Map data = jsonDecode(response.body);
if (data["Status"] == true) {
login = data["Data"];
logindtailsloading = true;
return LoginModel.fromJson(data["Data"]);
} else {
throw data;
}
} catch (e) {
print(e);
logindtailsloading = false;
loginDetailserror = true;
}
}
}
//here is getapi code
import 'package:http/http.dart' as http;
import 'package:officediaryapp/Models/NoticeModel.dart';
import 'dart:convert';
import 'package:officediaryapp/Utils/Api_Utils.dart';
class NoticeService {
bool error = false;
bool loading = true;
var notice;
bool noticeDetailserror = false;
bool noticeetailsloading = true;
Future<void> getNotice(dynamic input) async {
try {
noticeDetailserror = false;
http.Response response = await http.post(ApiUtils.noticeApi,
body: input, headers: {'Content-type': 'application/json'});
Map data = jsonDecode(response.body);
if (data["Status"] == true) {
notice = data["Data"];
notice = notice.map((_data) {
return new NoticeModel.fromJson(_data);
}).toList();
print(notice);
noticeetailsloading = false;
} else {
throw data;
}
} catch (e) {
print(e);
noticeetailsloading = false;
noticeDetailserror = true;
}
}
}
//here is post API code
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.