JSON
- JavaScript Object Notation, is a lightweight data interchange format that is easy for humans to read and write and easy for machines to parse and generate. It is a text format that is completely language independent but yses conventions that are familiar to programmers of the C family of languages, including C, C++, C#, Java, JavaScript, Perl, Python and many others.
JAON is often used to transmit data between a server and a web application, as an alternative to XML. JSON is represented as key-value pairs, where the keys are strings and teh values can be any valid JSON data type, including strings, numbers, Booleans, arrays, and objects. JSON is widely used in web development, mobile app development and other areas where data needs to be transmitted between different systems.
Example:
{
"name":"John",
"age":30
"car":null,
"address":{
"street":"Donald St.",
"city":"Cagayan de Oro City",
}
}
SAMPLE FREE PUBLIC API URL
https://catfact.ninja/fact
CODE:
import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Sample API'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
String _msg = "Message From API";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
children: [
const SizedBox(
height: 30,
),
Text(_msg),
ElevatedButton(
onPressed: () {
getMessageFromAPI();
},
child: const Text(
"Get Data",
),
)
],
),
),
);
}
void getMessageFromAPI() async {
String url = "https://catfact.ninja/fact";
try {
http.Response response = await http.get(Uri.parse(url));
if (response.statusCode == 200) {
setState(() {
Map<String, dynamic> cat = jsonDecode(response.body);
_msg = cat['fact'];
});
} else {
_msg = "${response.statusCode} ${response.reasonPhrase}";
}
} catch (error) {
setState(() {
_msg = "$error";
});
}
}
}
No comments:
Post a Comment