|
| 1 | +import 'package:flutter/material.dart'; |
| 2 | +import 'package:flutter_api_bridge/flutter_api_bridge.dart'; |
| 3 | + |
| 4 | +Future<void> main() async { |
| 5 | + WidgetsFlutterBinding.ensureInitialized(); |
| 6 | + |
| 7 | + await Server.init( |
| 8 | + baseUrl: 'https://jsonplaceholder.typicode.com', |
| 9 | + authStrategy: const CookieStrategy(), |
| 10 | + ); |
| 11 | + |
| 12 | + runApp(const MyApp()); |
| 13 | +} |
| 14 | + |
| 15 | +class MyApp extends StatelessWidget { |
| 16 | + const MyApp({super.key}); |
| 17 | + |
| 18 | + @override |
| 19 | + Widget build(BuildContext context) { |
| 20 | + return MaterialApp( |
| 21 | + title: 'Flutter API Bridge Example', |
| 22 | + theme: ThemeData( |
| 23 | + primarySwatch: Colors.blue, |
| 24 | + useMaterial3: true, |
| 25 | + ), |
| 26 | + home: const MyHomePage(title: 'API Bridge Example'), |
| 27 | + ); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +class MyHomePage extends StatefulWidget { |
| 32 | + const MyHomePage({super.key, required this.title}); |
| 33 | + |
| 34 | + final String title; |
| 35 | + |
| 36 | + @override |
| 37 | + State<MyHomePage> createState() => _MyHomePageState(); |
| 38 | +} |
| 39 | + |
| 40 | +class _MyHomePageState extends State<MyHomePage> { |
| 41 | + String _responseText = 'Press the button to make a request'; |
| 42 | + bool _isLoading = false; |
| 43 | + |
| 44 | + Future<void> _makeRequest() async { |
| 45 | + setState(() { |
| 46 | + _isLoading = true; |
| 47 | + _responseText = 'Loading...'; |
| 48 | + }); |
| 49 | + |
| 50 | + try { |
| 51 | + // Example: Fetch a todo from the JSON Placeholder API |
| 52 | + final response = await ApiClient.instance('').get('/todos/1'); |
| 53 | + |
| 54 | + setState(() { |
| 55 | + _isLoading = false; |
| 56 | + _responseText = 'Response: ${response.data}'; |
| 57 | + }); |
| 58 | + } catch (e) { |
| 59 | + setState(() { |
| 60 | + _isLoading = false; |
| 61 | + _responseText = 'Error: $e'; |
| 62 | + }); |
| 63 | + } |
| 64 | + } |
| 65 | + |
| 66 | + @override |
| 67 | + Widget build(BuildContext context) { |
| 68 | + return Scaffold( |
| 69 | + appBar: AppBar( |
| 70 | + title: Text(widget.title), |
| 71 | + ), |
| 72 | + body: Center( |
| 73 | + child: Column( |
| 74 | + mainAxisAlignment: MainAxisAlignment.center, |
| 75 | + children: <Widget>[ |
| 76 | + Padding( |
| 77 | + padding: const EdgeInsets.all(16.0), |
| 78 | + child: Text( |
| 79 | + _responseText, |
| 80 | + textAlign: TextAlign.center, |
| 81 | + style: Theme.of(context).textTheme.bodyMedium, |
| 82 | + ), |
| 83 | + ), |
| 84 | + ], |
| 85 | + ), |
| 86 | + ), |
| 87 | + floatingActionButton: FloatingActionButton( |
| 88 | + onPressed: _isLoading ? null : _makeRequest, |
| 89 | + tooltip: 'Make API Request', |
| 90 | + child: const Icon(Icons.api), |
| 91 | + ), |
| 92 | + ); |
| 93 | + } |
| 94 | +} |
0 commit comments