Flutter开发之——网络请求-手动json数据解析
import 'package:flutter/material.dart';
import 'dart:convert';
import 'package:http/http.dart' as http;
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
home: HomePage(),
);
}
}
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
String _data = "Loading...";
void _getData() async {
// 假设的网络请求URL
var url = "https://jsonplaceholder.typicode.com/posts/1";
var response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
// 解析JSON数据
var jsonResponse = jsonDecode(response.body);
// 更新UI上显示的数据
setState(() {
_data = jsonResponse['title'];
});
} else {
// 请求失败处理
_data = "Error: ${response.statusCode}";
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Fetch Data Example"),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
_data,
style: TextStyle(fontSize: 20),
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _getData,
tooltip: 'Get Data',
child: Icon(Icons.update),
),
);
}
}
这段代码使用了http
包来进行网络请求,并使用jsonDecode
来解析返回的JSON数据。当用户点击FloatingActionButton时,会触发_getData
方法,从指定的URL获取数据,然后解析并显示返回的JSON数据中的'title'字段。
评论已关闭