我是Flutter的新手,我想将API检索到的数据插入到字符串变量中,以供另一个函数使用。 谢谢您的帮助
我的代码是:------------
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'),
),
),
));
}
答案 0 :(得分:0)
您应该使用有状态的小部件来完成它。
以下代码可能为您带来更多帮助。
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),
),
);
}
}
答案 1 :(得分:0)
这将很好地工作,请检查一下:
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(),
);
},
),
);
}
}
答案 2 :(得分:0)
从 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,
)
],
),
),
);
}
}
上传到 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),
);
}),
),
),
),
);
}
}
使用参数获取
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'];
});
}
}
//访问 listfacts[index]['Data']),
答案 3 :(得分:0)
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