Category: Flutter

  • API testing in Flutter

    API testing in Flutter

    It is very common to use API in our Flutter projects. Testing makes the Flutter project very easy to maintain, in this way you will save a lot of debugging time. Also when you have testing in place you can always check whether API working as expected. 

    Let’s create a simple API endpoint in PHP in our local server. If you don’t anything about PHP web development, It’s quite fun to work in PHP. This PHP file just responds with a JSON which has a list of Books, nothing complex right? 

    Server:

    <?php
    
    $b1 = ['title' => 'Beginning App Development with Flutter', 'author' => 'Rap Payne'];
    $b2 = ['title' => 'Beginning Flutter: A Hands On Guide to App Development', 'author' => 'Marco L. Napoli'];
    $b2 = ['title' => 'Flutter Apprentice', 'author' => 'Vincenzo Guzzi, Kevin D Moore, Vincent Ngo and Michael Katz'];
    
    $books = [$b1, $b2];
    
    header("content-type: application/json; charset=UTF-8");
    echo json_encode($books, JSON_PRETTY_PRINT);
    
    [
        {
            "title": "Beginning App Development with Flutter",
            "author": "Rap Payne"
        },
        {
            "title": "Flutter Apprentice",
            "author": "Vincenzo Guzzi, Kevin D Moore, Vincent Ngo and Michael Katz"
        }
    ]

    Flutter:


    Let’s first create a flutter project called “api_test”, we will use VSCode for the rest of the project.

    flutter create api_test

    Let’s add http package by this command, run on your terminal.

    flutter pub add http

    Go to your lib folder and create two files model.dart and service.dart.

    Model: 

    On the model.dart creates a book class.

    class Book {
      final String title;
      final String author;
    
      Book({required this.title, required this.author});
    }

    API:

    In the service, class create an abstract class like this 

    abstract class BookApi {
    import 'package:api_test/model.dart';
    import 'package:http/http.dart' as http;
    import 'dart:convert' as convert;
    
    abstract class BookApi {
      Future<List<Book>> books();
    }
    
    class BookService implements BookApi {
      Future<List<Book>> books() async {
        var url = Uri.parse('http://localhost/flutter/book.php');
        var response = await http.get(url);
    
        //print(response.body);
        if (response.statusCode == 200) {
          final listResponse = convert.jsonDecode(response.body) as List;
          List<Book> books = listResponse
              .map(
                (e) => Book(
                  title: e['title'],
                  author: e['author'],
                ),
              )
              .toList();
          return books;
        } else {
          print('Request failed with status: ${response.statusCode}.');
          return [];
        }
      }
    }
    
    

    create another class in the same file for the above BookApi method implementation

    Test:

    Create a test file called book_service_test.dart in test folder

    import 'package:api_test/model.dart';
    import 'package:api_test/service.dart';
    import 'package:flutter_test/flutter_test.dart';
    
    void main() {
      var book_service = BookService();
    
      test('book api', () async {
        final result = await book_service.books();
        print(" test $result");
    
        expect(result.isNotEmpty, true);
        expect(result, isA<List<Book>>());
      });
    }
    

    Our tests are passed when the list is not empty and list has a book type.

    Download the full source code

    Spread the love
  • Call swift native code from Flutter

    In this tutorial, we are going to call a simple swift method of AppDelegate.swift file from flutter.

    Let’s create a brand new flutter app by running the following command on your terminal

    flutter create ios_native

    Delete everything inside the method _incrementCounter() on your main.dart file and make it an async method.

     Future<void> _incrementCounter() async {
        const MethodChannel _channel =
            const MethodChannel("FlutterFramework/swift_native");
        final result = await _channel.invokeMethod('getSum');
        print("result from iOS native + Swift ${result}");
      }

    Now open your Runner.xcworkspace on Xcode and open AppDelegate.swift

    private func getSum() -> Int {
        return 2 + 2
     }

    Add the following code in the method didFinishLaunchingWithOptions and close the Xcode.

     let controller : FlutterViewController = window?.rootViewController as! FlutterViewController
          let channel = FlutterMethodChannel(name: "FlutterFramework/swift_native",
                                             binaryMessenger: controller.binaryMessenger)
          channel.setMethodCallHandler({
              [weak self]  (call: FlutterMethodCall, result: @escaping FlutterResult) -> Void in
              // This method is invoked on the UI thread.
              // Handle battery messages.
              guard call.method == "getSum" else {
                  result(FlutterMethodNotImplemented)
                  return
              }
    
              result(self?.getSum())
          })

    Now run the flutter app on the VSCode or Android Studio, if you click the floating button you will swift method returns 2 +2 = 4

    Call native Android code from Flutter

    Spread the love
  • How to change the status bar color in Flutter, Android only

    Changing the status bar color is very easy in Flutter. There are a few ways to do this.

    1. Globally in the main function
    import 'package:flutter/services.dart';
    
    void main() {
    
      SystemChrome.setSystemUIOverlayStyle(
        SystemUiOverlayStyle(
          statusBarColor: Colors.red,
        ),
      );
    
      runApp(
        MyApp()
      );
    }

    2. Globally in the MaterialApp widget in ThemeData

    return MaterialApp(
          title: 'FlutterFramework',
          debugShowCheckedModeBanner: false,
          themeMode: ThemeMode.light,
          theme: ThemeData(
            primaryColor: Colors.red,
            appBarTheme: AppBarTheme(
              systemOverlayStyle: SystemUiOverlayStyle(
                statusBarColor: Colors.red,
              ),
            ),
          ),
    );

    3. AppBar only

    AppBar(
      systemOverlayStyle: SystemUiOverlayStyle(
        statusBarColor: Colors.red,
      ),
    )

    Spread the love