Connecting Your App to the World

Fetching Data from APIs: Using http and Other Libraries

Modern apps often rely on external APIs to fetch or send data. Flutter makes this easy with the http package and other networking libraries.

  1. Add the http package to your pubspec.yaml:
  2. 
    dependencies:
      http: ^1.2.0
        
  3. Fetch data from an API:
  4. 
    import 'package:http/http.dart' as http;
    import 'dart:convert';
    
    Future<List<dynamic>> fetchPosts() async {
      final response = await http.get(Uri.parse('https://jsonplaceholder.typicode.com/posts'));
      
      if (response.statusCode == 200) {
        return jsonDecode(response.body);
      } else {
        throw Exception('Failed to load posts');
      }
    }
        
  5. Display the data in a widget using FutureBuilder:
  6. 
    FutureBuilder(
      future: fetchPosts(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        } else if (snapshot.hasError) {
          return Text('Error: \${snapshot.error}');
        } else {
          final posts = snapshot.data as List;
          return ListView.builder(
            itemCount: posts.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(posts[index]['title']),
                subtitle: Text(posts[index]['body']),
              );
            },
          );
        }
      },
    )
        

Real-time Communication: WebSockets and Firebase Integration

Real-time communication is essential for chat apps, live dashboards, and collaborative tools.

  • WebSockets: Flutter supports WebSockets through the web_socket_channel package.
    
    import 'package:web_socket_channel/web_socket_channel.dart';
    
    final channel = WebSocketChannel.connect(Uri.parse('wss://echo.websocket.events'));
    
    StreamBuilder(
      stream: channel.stream,
      builder: (context, snapshot) {
        return Text(snapshot.hasData ? '${snapshot.data}' : '');
      },
    );
          
  • Firebase: Use Firebase's Cloud Firestore or Realtime Database for automatic synchronization and push updates.
    
    // Example with Firestore
    StreamBuilder(
      stream: FirebaseFirestore.instance.collection('messages').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return CircularProgressIndicator();
        final docs = snapshot.data!.docs;
        return ListView.builder(
          itemCount: docs.length,
          itemBuilder: (context, index) {
            return ListTile(title: Text(docs[index]['text']));
          },
        );
      },
    );
          

Local Storage: Managing Data Persistence with Hive and Shared Preferences

Persisting data locally is useful for storing user settings, cached data, or offline content.

  • Shared Preferences: Key-value storage for small amounts of simple data.
    
    final prefs = await SharedPreferences.getInstance();
    await prefs.setString('username', 'Amine');
    final username = prefs.getString('username');
          
  • Hive: A lightweight, NoSQL database for Flutter apps.
    
    var box = await Hive.openBox('settings');
    box.put('theme', 'dark');
    var theme = box.get('theme');
          

By integrating API calls, real-time communication, and local storage, your Flutter apps can stay connected, responsive, and user-friendly in any scenario.

Post a Comment

0 Comments