SoloBits Share | Learn | Contribute

Uniform Text Sizes Across the App in Flutter

If you’re new to Flutter or a Pro we know how much of the Text Widget we use… Some large in size, some small, some bold and the list goes on. Having uniform text sizes and attributes across the app is very important for the UI/UX. So I just decided to share a small tip for new devs on who can they do it.

We’re are simply going to create a Text widget in our project that we can then call across our app.

Create a new file called text.dart

import 'package:flutter/material.dart';

//Enum for different text types, you can add more
enum TextType { sm, body, subtitle, title, xl }

const double fontSize = 14.0;
// Inspired by VelocityX
// Scale factors as found in VelocityX package
const double scaleFactorBase = 1;
const double scaleFactorLg = 1.120;
const double scaleFactorXl = 1.25;
const double scaleFactorXl2 = 1.5;
const double scaleFactorXl3 = 1.875;
const double scaleFactorXl4 = 2.25;
const double scaleFactorXl5 = 3;
const double scaleFactorXl6 = 4;

class AppText extends StatelessWidget {
  //some common attributes. You can change as needed
  final String text;
  final TextType type;
  final Color color;
  final TextAlign align;
  final double scaleFactor;
  final FontWeight weight;
  final bool underline;

  const AppText(
      {@required this.text,
      @required this.type,
      this.color,
      this.align,
      this.scaleFactor,
      this.weight,
      this.underline = false,
      Key key})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Text(text,
        style: TextStyle(
            color: color ?? _colorByTextType(type),
            fontSize: fontSize,
            fontWeight: weight ?? FontWeight.normal,
            decoration: underline ? TextDecoration.underline : null),
        textScaleFactor: scaleFactor ?? _scaleFactorByTextType(type),
        textAlign: align ?? TextAlign.start);
  }

  Color _colorByTextType(TextType type) {
    Color _color = Colors.black87;

    switch (type) {
      case TextType.sm:
        _color = Colors.white;
        break;
      case TextType.body:
        _color = Colors.black;
        break;
      case TextType.subtitle:
        _color = Colors.red;
        break;
      case TextType.title:
        _color = Colors.green;
        break;
      case TextType.xl:
        _color = Colors.blue;
        break;
      default:
        break;
    }

    return _color;
  }

  double _scaleFactorByTextType(TextType type) {
    double _factor = scaleFactorBase;

    switch (type) {
      case TextType.sm:
        _factor = scaleFactorBase;
        break;
      case TextType.body:
        _factor = scaleFactorLg;
        break;
      case TextType.subtitle:
        _factor = scaleFactorXl;
        break;
      case TextType.title:
        _factor = scaleFactorXl2;
        break;
      case TextType.xl:
        _factor = scaleFactorXl3;
        break;
      default:
        break;
    }

    return _factor;
  }
}

Usage

Now in any file of you project simply call AppText widget. e.g:

 cosnt AppText(text: 'Some Text',
         type: TextType.title,
         color: Colors.pink,
         weight: FontWeight.w600,
        align: TextAlign.center)

Share with us below on how you have been solving this problem. 🙂 Hope it helps.

  •   

Image Text Recognition in Flutter

Recently while working on a project, I was assigned a task to implement text recognition also called OCR(Optical Character Recognition). For this task I chose Firebase ML.

Firebase ML

Firebase ML provides us:

  • Text recognition
  • Image labeling
  • Object detection and tracking
  • Face detection and contour tracing
  • Barcode scanning
  • Language identification
  • Translation
  • Smart Reply

For more info: https://firebase.google.com/docs/ml

Text recognition

In this tutorial we’ll be doing a very basic implementaion of Text Recognition.

Importing Package

In pubspec.yaml import Image Picker and ML Vision packages. pubspec will then look something like this:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  image_picker: ^0.6.7+4
  firebase_ml_vision: ^0.9.4

dev_dependencies:
  flutter_test:
    sdk: flutter

    

Firebase Setup

If you’ve already set up firebase then skip, else follow this article.
https://solobits.github.io/2020/07/13/firebase/

Text Recognition Implementation

/...
import 'dart:io';

import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';

/...

// In any Widget of your's return 

Scaffold(
        body: Center(
          child: RaisedButton(
            onPressed: () async {
              

              //Pick an image
              final picker = ImagePicker();

              final pickedFile =
                  await picker.getImage(source: ImageSource.camera);
                  
                  
              //OCR implementation
              //TODO catch errors
              final FirebaseVisionImage visionImage =
                  FirebaseVisionImage.fromFile(File(pickedFile.path));

              final TextRecognizer textRecognizer =
                  FirebaseVision.instance.textRecognizer();

              final VisionText recognizedText =
                  await textRecognizer.processImage(visionImage);

              //Text will be displayed in the debug console     
              debugPrint(recognizedText.text);
            },
            child: const Text('Get OCR Text'),
          ),
        ),
      )

That’s it, cheers. 🍻 Simple isn’t it.

Hope it helps.

Basic Firebase Setup

In this article, we’ll set up our Flutter App with basic Firebase Configuration.

Create Firebase Account

1- Browse https://firebase.google.com and click ‘Go To Console’ after you’ve signed in.
2- Click Add Project.
3- Name your Project and click next.
4- Enable Google analytics in the next step if you want and then continue.
5- Create or select an Analytics account and create your project.

Android Firebase Setup

1- In your Project Overview screen add an Android App.
2- Register your App’s package name e.g com.solobits.firebase_app, Enter your App’s name, Signing Certificate is optional but if you need to add it follow this URL https://developers.google.com/android/guides/client-auth, Once done click Register App.
3- Download the google-services.json file and paste it in your project/android/app directory. When done, click next.
4- Paste the code in you app-level gradle and project-level gradle as defined in the step.
5- Done!! You can skip the last step.
For in-depth article visit: https://firebase.google.com/docs/flutter/setup?platform=android

iOS Firebase Setup

For iOS setup, you need to have XCode on your Mac.

1- In your Project Overview screen add an iOS App.
2- Register your App’s package name e.g com.solobits.firebaseapp, Enter your App’s name, App Store ID is optional for now, Once done click Register App.
3- Download the GoogleService-Info.plist file. Now using XCode and paste it in your Runner/Runner directory.
4- Done!! You can skip the last step.
For in-depth article visit: https://firebase.google.com/docs/flutter/setup?platform=ios

Routing Using Get

Routing in Flutter can be easy for small apps, but when you have quite a few pages you know that you need to manage them properly. Flutter gives you quite a few ways to do that, you might be doing it by using named routes or a package like auto_route. For this article, we’ll be using GET.

GET, Router

GET is not just a simple Routing solution but a Micro-Framework for Flutter. It has quite a lot that we can do with it like Dependency Management, State Management, Utils/Helpers and more.

Routing

We’ll start by creating a new Flutter project.

Importing Package

In pubspec.yaml import GET package. pubspec will then look something like this:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  get: ^3.2.2

dev_dependencies:
  flutter_test:
    sdk: flutter

    

Base Setup

In your main.dart rename MaterialApp to GetMaterialApp.

import 'package:get/route_manager.dart';

import 'package:demo/routes.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      initialRoute: routeOne,
      getPages: generateRoutes
    );
  }
}

Create a routes.dart file

import 'package:get/route_manager.dart';

import 'package:demo/pages/one_page.dart';
import 'package:demo/pages/two_page.dart';

const String routeOne = '/';
const String routeTwo = '/two';
mixin AppRoutes {
  final List<GetPage> generateRoutes = [
    GetPage(
        name: routeOne,
        page: () => const PageOne()),
        GetPage(
        name: routeTwo,
        page: () => const PageTwo()),
   
  ];
}

Now simply call Get.toNamed to navigate to a page or Get.offNamed to push to new page and replace current page.

//Navigator.pushNamed 
FlatButton(onPressed: () => Get.toNamed(page))
//Navigator.pushReplacementNamed 
FlatButton(onPressed: () => Get.offNamed(page))

Previous Articles on GET

State Management using GET

Upcoming Articles

I’ll be writing a list of Articles that will cover almost everything that we can do with GET namingly:

  • Dependency Management
  • Other Fun Helpers/Utilities (SnackBars, Dialog, BottomSheet etc)
  • Architecture using GET

Hope it helps.

State Management Using Get

The following article assumes you are already aware of State Management Basics. We’ll be using a package called GET for this article.

If you want to learn about the basics follow the official Flutter documentation which explains State Management very good: https://flutter.dev/docs/development/data-and-backend/state-mgmt

GET, Juiced State Manager

We do have multiple options to achieve this namingly InheritedWidgets, ScopedModel, Provider, Bloc, MobX etc. But we’ll be using GET which is not just a simple State Management solution but a Micro-Framework for Flutter. It has quite a lot that we can do with it like Dependency Management, Router, Utils/Helpers and more.

So basically GET is on Steroids. We’ll start by talking about how it can help us manage our state.

State Management

We’ll start by creating a new Flutter project. We’ll use the default counter app and modify it using GET.

Importing Package

In pubspec.yaml import GET package. pubspec will then look something like this:

environment:
  sdk: ">=2.7.0 <3.0.0"

dependencies:
  flutter:
    sdk: flutter

  cupertino_icons: ^0.1.3
  get:

dev_dependencies:
  flutter_test:
    sdk: flutter

Base Setup

In your main.dart rename MaterialApp to GetMaterialApp.

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(),
    );
  }
}

Create your ViewModel/Controller

Our ViewModel will have our business logic. Create getters and setters for the counter variable.

class CounterViewmodel extends GetController {
  int _counter = 0;

  int get counter => _counter;
  set counter(int val) {
    _counter = val;
    update();
  }
}

Wrap the widget you want to update in GetBuilder

GetBuilder<CounterViewmodel>( //It's something like a consumer that we use in Provider
              init: CounterViewmodel(),
              builder: (_) => Text(
                '${_.counter}',
                style: Theme.of(context).textTheme.headline4,
              ),
            ),
            

To trigger an increment we’ll do something like this

floatingActionButton: FloatingActionButton(
        onPressed: () {
          final _viewmodel = Get.find<CounterViewmodel>(); //Just like we use Provider.of for Provider

          _viewmodel.counter = _viewmodel.counter + 1;
        },
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
      

Run your app and Voila!. That’s all you need.

Upcoming Articles

I’ll be writing a list of Articles that will cover almost everything that we can do with GET namingly:

  • Dependency Management
  • Router
  • Other Fun Helpers/Utilities (SnackBars, Dialog, BottomSheet etc)
  • Architecture using GET

Hope it helps.

Source Code