我是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'),
),
),
));
}
您应该使用有状态的小部件来完成它。
以下代码可能会为您提供更多帮助。
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),
),
);
}
}