Sunday, June 4, 2023

Building a Flutter App with RESTful API Integration: A Complete Guide


This task involves creating a Flutter app that interacts with a RESTful API. The app retrieves data from the API and displays it in a list view. It also allows users to create new data by sending a POST request to the API. The app includes functionality to fetch data from the API, display it in a list, and create new data through user input. The code provided demonstrates how to implement these features using Flutter and the http package for API communication.

import 'dart:convert';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'RESTful API Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<dynamic> _data = [];

  Future<void> fetchData() async {
    final response = await http.get(Uri.parse('https://api.example.com/data'));

    if (response.statusCode == 200) {
      setState(() {
        _data = jsonDecode(response.body);
      });
    } else {
      throw Exception('Failed to load data');
    }
  }

  Future<void> createData(String name, String description) async {
    final response = await http.post(
      Uri.parse('https://api.example.com/data'),
      body: jsonEncode({'name': name, 'description': description}),
      headers: {'Content-Type': 'application/json'},
    );

    if (response.statusCode == 201) {
      fetchData(); // Refresh data after successful creation
    } else {
      throw Exception('Failed to create data');
    }
  }

  @override
  void initState() {
    super.initState();
    fetchData();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('RESTful API Example'),
      ),
      body: Column(
        children: [
          Expanded(
            child: ListView.builder(
              itemCount: _data.length,
              itemBuilder: (BuildContext context, int index) {
                final item = _data[index];
                return ListTile(
                  title: Text(item['name']),
                  subtitle: Text(item['description']),
                );
              },
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                TextField(
                  decoration: InputDecoration(
                    labelText: 'Name',
                  ),
                  onChanged: (value) {
                    // Update name variable
                  },
                ),
                TextField(
                  decoration: InputDecoration(
                    labelText: 'Description',
                  ),
                  onChanged: (value) {
                    // Update description variable
                  },
                ),
                ElevatedButton(
                  onPressed: () {
                    createData(name, description);
                  },
                  child: Text('Create'),
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

In this updated code, a new createData() function is added to send a POST request to the API when the user clicks the "Create" button. The function takes the name and description as parameters, encodes them as JSON in the request body, and sets the appropriate content-type headers.

Inside the build() method, a new column is added at the bottom of the screen with two TextField widgets for the user to enter the name and description of the new data. The values from these fields can be stored in variables and used in the createData() function to create new data when the button is pressed.

Remember to replace the API URL with the actual endpoint of your RESTful API, and make sure to import the necessary dependencies in your pubspec.yaml file.

 

 

 

No comments:

Post a Comment

Enhancing Flutter Apps with BLoC State Management and REST APIs for Optimal Performance

 Develop a powerful Flutter app utilizing BLoC state management and REST APIs to enhance functionality and performance. Flutter app using th...