dependencies:
flutter:
sdk: flutter
http: ^0.13.3
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Cat Fact App',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: CatFactPage(),
);
}
}
class CatFactPage extends StatefulWidget {
@override
_CatFactPageState createState() => _CatFactPageState();
}
class _CatFactPageState extends State<CatFactPage> {
String? _catFact;
@override
void initState() {
super.initState();
_fetchCatFact();
}
Future<void> _fetchCatFact() async {
final response = await http.get(Uri.parse('https://catfact.ninja/fact'));
if (response.statusCode == 200) {
final data = json.decode(response.body);
setState(() {
_catFact = data["fact"];
});
} else {
print('Failed to load cat fact');
}
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Cat Fact App'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
// Cat Image
Container(
child: Image.network(
'https://placekitten.com/200/200'), // a placeholder cat image
margin: EdgeInsets.only(bottom: 20.0),
),
// Cat Fact Text
Padding(
padding:
const EdgeInsets.symmetric(horizontal: 20.0, vertical: 10.0),
child: _catFact == null
? CircularProgressIndicator()
: Text(
_catFact!,
style: TextStyle(fontSize: 18),
textAlign: TextAlign.center,
),
),
// Button to Fetch New Fact
ElevatedButton(
onPressed: _fetchCatFact,
child: Text('Get New Fact'),
)
],
),
);
}
}