A Page Slider with Parallex Design For Flutter

Flutter OnBoarding Slider is a Flutter package containing a page slider with parallex design that allows (Text) widgets or body to slide at a different speed with background. ✨

Supporting Android, iOS.

Why?

We build this package because we wanted to:

  • have parralex design of the background that allows background to slide at a different speed.
  • display with a bottom controller that indicates the current page.
  • trigger skip with a button on the top right with a final function.
  • NEW: you can use centerBackground property to center the background images. If you use this property imageHorizontalOffset property will get ignored.
  • NEW: You can use finishButtonStyle property to customize the finish button according to your design.

Show Cases

Swipe

Touch swiping.

Slide

Swipe with the Floating Action Button.

Skip

Skip to last Slide.

Installation

Create a new project with the command

flutter create MyApp

Add

dependencies:
  ...
  flutter_onboarding_slider:

to your pubspec.yaml of your flutter project. OR run

flutter pub add flutter_onboarding_slider

in your project's root directory.

In your library add the following import:

import 'package:flutter_onboarding_slider/flutter_onboarding_slider.dart';

For help getting started with Flutter, view the online documentation.

Usage

You can place your OnBoardingSlider inside of a Scaffold or CupertinoApp like we did here. Optional parameters can be defined to enable different features. See the following example..

class OnBoarding extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return CupertinoApp(
      home: OnBoardingSlider(
        headerBackgroundColor: Colors.white,
        finishButtonText: 'Register',
        finishButtonStyle: FinishButtonStyle(
          backgroundColor: Colors.black,
        ),
        skipTextButton: Text('Skip'),
        trailing: Text('Login'),
        background: [
          Image.asset('assets/slide_1.png'),
          Image.asset('assets/slide_2.png'),
        ],
        totalPage: 2,
        speed: 1.8,
        pageBodies: [
          Container(
            padding: EdgeInsets.symmetric(horizontal: 40),
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 480,
                ),
                Text('Description Text 1'),
              ],
            ),
          ),
          Container(
            padding: EdgeInsets.symmetric(horizontal: 40),
            child: Column(
              children: <Widget>[
                SizedBox(
                  height: 480,
                ),
                Text('Description Text 2'),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Constructor

Basic

ParameterDefaultDescriptionRequired
headerBackgroundColor-color of the backgroundfalse
finishButtonText-Text inside last pages bottom buttonfalse
skipTextButton-NavigationBar trailing widget when not on last screenfalse
trailing-NavigationBar trailing widget when on last screenfalse
background-List of Widgets to be shown in the backgrounds of the pages. For example a picture or some illustrationtrue
totalPage-Number of total pagestrue
speed-The speed of the animation for the [background]true
pageBodies-The main content ont the screen displayed above the [background]true
centerBackgroundfalseThis flag is used to center the background.false
finishButtonStyle-This property is used to customize the finish button.false

Made with ❤ by Flutter team at Appinio GmbH

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_onboarding_slider

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_onboarding_slider: ^1.0.9

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_onboarding_slider/flutter_onboarding_slider.dart';

example/lib/main.dart

import 'package:example/screens/login_page.dart';
import 'package:example/screens/register_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_onboarding_slider/flutter_onboarding_slider.dart';

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

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return const CupertinoApp(
      debugShowCheckedModeBanner: false,
      home: MyHome(),
    );
  }
}

class MyHome extends StatelessWidget {
  final Color kDarkBlueColor = const Color(0xFF053149);

  const MyHome({super.key});

  @override
  Widget build(BuildContext context) {
    return OnBoardingSlider(
      finishButtonText: 'Register',
      onFinish: () {
        Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => const RegisterPage(),
          ),
        );
      },
      finishButtonStyle: FinishButtonStyle(
        backgroundColor: kDarkBlueColor,
      ),
      skipTextButton: Text(
        'Skip',
        style: TextStyle(
          fontSize: 16,
          color: kDarkBlueColor,
          fontWeight: FontWeight.w600,
        ),
      ),
      trailing: Text(
        'Login',
        style: TextStyle(
          fontSize: 16,
          color: kDarkBlueColor,
          fontWeight: FontWeight.w600,
        ),
      ),
      trailingFunction: () {
        Navigator.push(
          context,
          CupertinoPageRoute(
            builder: (context) => const LoginPage(),
          ),
        );
      },
      controllerColor: kDarkBlueColor,
      totalPage: 3,
      headerBackgroundColor: Colors.white,
      pageBackgroundColor: Colors.white,
      background: [
        Image.asset(
          'assets/slide_1.png',
          height: 400,
        ),
        Image.asset(
          'assets/slide_2.png',
          height: 400,
        ),
        Image.asset(
          'assets/slide_3.png',
          height: 400,
        ),
      ],
      speed: 1.8,
      pageBodies: [
        Container(
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.symmetric(horizontal: 40),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const SizedBox(
                height: 480,
              ),
              Text(
                'On your way...',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: kDarkBlueColor,
                  fontSize: 24.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              const Text(
                'to find the perfect looking Onboarding for your app?',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black26,
                  fontSize: 18.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
        Container(
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.symmetric(horizontal: 40),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const SizedBox(
                height: 480,
              ),
              Text(
                'You’ve reached your destination.',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: kDarkBlueColor,
                  fontSize: 24.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              const Text(
                'Sliding with animation',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black26,
                  fontSize: 18.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
        Container(
          alignment: Alignment.center,
          width: MediaQuery.of(context).size.width,
          padding: const EdgeInsets.symmetric(horizontal: 40),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: <Widget>[
              const SizedBox(
                height: 480,
              ),
              Text(
                'Start now!',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: kDarkBlueColor,
                  fontSize: 24.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
              const SizedBox(
                height: 20,
              ),
              const Text(
                'Where everything is possible and customize your onboarding.',
                textAlign: TextAlign.center,
                style: TextStyle(
                  color: Colors.black26,
                  fontSize: 18.0,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ],
          ),
        ),
      ],
    );
  }
}

Download details:

Author: appinio.app

Source: https://github.com/appinioGmbH/flutter_packages/tree/main/packages/flutter_onboarding_slider

#flutter #android #web-development #web #ui 

A Page Slider with Parallex Design For Flutter

Pre-built Widgets /Utilites to Integrate Firebase Firestore In Flutter

Firebase UI for Firestore 

Firebase UI for Firestore enables you to easily integrate your application UI with your Cloud Firestore database.

Installation

flutter pub add cloud_firestore
flutter pub add firebase_ui_firestore

Usage

Import the Firebase UI for Firestore package:

import 'package:firebase_ui_firestore/firebase_ui_firestore.dart';

Infinite scrolling

Infinite scrolling is the concept of continuously loading more data from a database as the user scrolls through your application. This is useful when you have a large datasets, as it enables the application to render faster as well as reduces network overhead for data the user might never see.

Firebase UI for Firestore provides a convenient way to implement infinite scrolling using the Firestore database with the FirestoreListView widget.

At a minimum the widget accepts a Firestore query and an item builder. As the user scrolls down (or across) your list, more data will be automatically fetched from the database (whilst respecting query conditions such as ordering).

To get started, create a query and provide an item builder. For this example, we'll display a list of users from the users collection:

final usersQuery = FirebaseFirestore.instance.collection('users').orderBy('name');

FirestoreListView<Map<String, dynamic>>(
  query: usersQuery,
  itemBuilder: (context, snapshot) {
    Map<String, dynamic> user = snapshot.data();

    return Text('User name is ${user['name']}');
  },
);

The FirestoreListView widget is built on-top of Flutter's own ListView widget, and accepts the same parameters which we can optionally provide. For example, to change the scroll-direction to horizontal:

FirestoreListView<Map<String, dynamic>>(
  scrollDirection: Axis.horizontal,
  // ...
);

Controlling page size

By default, the widget will fetch 10 items from the collection at a time. This can be changed by providing a pageSize parameter:

FirestoreListView<Map<String, dynamic>>(
  pageSize: 20,
  // ...
);

In general, it is good practice to keep this value as small as possible to reduce network overhead. If the height (or width) of an individual item is large, it is recommended to lower the page size.

Using typed responses

The cloud_firestore plugin allows us to type the responses we receive from the database using the withConverter API. For more information, see the documentation.

The FirestoreListView works with this out of the box. Simply provide a converted query to the widget, for example:

class User {
  User({required this.name, required this.age});

  User.fromJson(Map<String, Object?> json)
    : this(
        name: json['name']! as String,
        age: json['age']! as int,
      );

  final String name;
  final int age;

  Map<String, Object?> toJson() {
    return {
      'name': name,
      'age': age,
    };
  }
}

final usersQuery = FirebaseFirestore.instance.collection('users')
  .orderBy('name')
  .withConverter<User>(
     fromFirestore: (snapshot, _) => User.fromJson(snapshot.data()!),
     toFirestore: (user, _) => user.toJson(),
   );

FirestoreListView<User>(
  query: usersQuery,
  itemBuilder: (context, snapshot) {
    // Data is now typed!
    User user = snapshot.data();

    return Text(user.name);
  },
);

Loading and error handling

By default, the widget will display a loading indicator while data is being fetched from the database, and ignore any errors which might be thrown (such as permission denied). You can override this behavior by providing a loadingBuilder and errorBuilder parameters to the widget:

FirestoreListView<Map<String, dynamic>>(
  loadingBuilder: (context) => MyCustomLoadingIndicator(),
  errorBuilder: (context, error, stackTrace) => MyCustomError(error, stackTrace),
  // ...
);

Advanced configuration

In many cases, the FirestoreListView widget is enough to render simple lists of collection data. However, you may have specific requirements which require more control over the widget's behavior (such as using a GridView).

The FirestoreQueryBuilder provides the building blocks for advanced configuration at the expense of requiring more boilerplate code. The widget does not provide any underlying list implementation, instead you are expected to provide this yourself.

Much like the FirestoreListView widget, provide a query and builder:

final usersQuery = FirebaseFirestore.instance.collection('users').orderBy('name');

FirestoreQueryBuilder<Map<String, dynamic>>(
  query: usersQuery,
  builder: (context, snapshot, _) {
    // ... TODO!
  },
);

The main difference to note here is that the builder property returns a QueryBuilderSnapshot, rather than an individual document. The builder returns the current state of the entire query, such as whether data is loading, an error has occurred and the documents.

This requires us to implement our own list based implementation. Firstly, let's handle the loading and error states:

FirestoreQueryBuilder<Map<String, dynamic>>(
  query: usersQuery,
  builder: (context, snapshot, _) {
    if (snapshot.isFetching) {
      return const CircularProgressIndicator();
    }

    if (snapshot.hasError) {
      return Text('Something went wrong! ${snapshot.error}');
    }

    // ...
  },
);

Next, we now need to return a list-view based implementation for our application to display the data. For example, to display a grid of users, we can use the GridView widget:

FirestoreQueryBuilder<Map<String, dynamic>>(
  query: usersQuery,
  builder: (context, snapshot, _) {
    // ...

    return GridView.builder(
      itemCount: snapshot.docs.length,
      itemBuilder: (context, index) {
        // if we reached the end of the currently obtained items, we try to
        // obtain more items
        if (snapshot.hasMore && index + 1 == snapshot.docs.length) {
          // Tell FirestoreQueryBuilder to try to obtain more items.
          // It is safe to call this function from within the build method.
          snapshot.fetchMore();
        }

        final user = snapshot.docs[index].data();

        return Container(
          padding: const EdgeInsets.all(8),
          color: Colors.teal[100],
          child: const Text("User name is ${user['name']}"),
        );
      },
    );
  },
);

With more power comes more responsibility:

  1. Within the itemBuilder of our GridView, we have to manually ensure that we call the fetchMore() method on the snapshot when more data is required.
  2. The FirestoreQueryBuilder does not provide a list-view based handler, instead you must provide your own implementation.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add firebase_ui_firestore

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  firebase_ui_firestore: ^1.5.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:firebase_ui_firestore/firebase_ui_firestore.dart';

example/lib/main.dart

// Copyright 2022, the Chromium project authors.  Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_ui_firestore/firebase_ui_firestore.dart';
import 'package:firebase_ui_firestore_example/firebase_options.dart';
import 'package:flutter/material.dart';

late CollectionReference<User> collection;

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  final collectionRef = FirebaseFirestore.instance.collection('users');

  collection = collectionRef.withConverter<User>(
    fromFirestore: (snapshot, _) => User.fromJson(snapshot.data()!),
    toFirestore: (user, _) => user.toJson(),
  );

  runApp(const FirebaseUIFirestoreExample());
}

class FirebaseUIFirestoreExample extends StatelessWidget {
  const FirebaseUIFirestoreExample({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Contacts')),
        body: FirestoreListView<User>(
          query: collection,
          padding: const EdgeInsets.all(8.0),
          itemBuilder: (context, snapshot) {
            final user = snapshot.data();
            return Column(
              children: [
                UserTile(user: user),
                const Divider(),
              ],
            );
          },
        ),
      ),
    );
  }
}

class UserTile extends StatelessWidget {
  final User user;
  const UserTile({
    super.key,
    required this.user,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        CircleAvatar(
          child: Text(user.firstName[0]),
        ),
        const SizedBox(width: 8),
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          mainAxisAlignment: MainAxisAlignment.center,
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(
              '${user.firstName} ${user.lastName}',
              style: Theme.of(context).textTheme.titleMedium,
            ),
            Text(
              user.number,
              style: Theme.of(context).textTheme.bodySmall,
            ),
          ],
        ),
      ],
    );
  }
}

class User {
  User({
    required this.city,
    required this.country,
    required this.streetName,
    required this.zipCode,
    required this.prefix,
    required this.firstName,
    required this.lastName,
    required this.email,
    required this.userName,
    required this.number,
  });
  User.fromJson(Map<String, Object?> json)
      : this(
          city: json['city'].toString(),
          country: json['country'].toString(),
          streetName: json['streetName'].toString(),
          zipCode: json['zipCode'].toString(),
          prefix: json['prefix'].toString(),
          firstName: json['firstName'].toString(),
          lastName: json['lastName'].toString(),
          email: json['email'].toString(),
          userName: json['userName'].toString(),
          number: json['number'].toString(),
        );

  final String city;
  final String country;
  final String streetName;
  final String zipCode;

  final String prefix;
  final String firstName;
  final String lastName;

  final String email;
  final String userName;
  final String number;

  Map<String, Object?> toJson() {
    return {
      'city': city,
      'country': country,
      'streetName': streetName,
      'zipCode': zipCode,
      'prefix': prefix,
      'firstName': firstName,
      'lastName': lastName,
      'email': email,
      'userName': userName,
      'number': number,
    };
  }
}

Download details:

Author: firebase.google.com

Source: https://github.com/firebase/flutterfire/tree/master/packages/firebase_ui_firestore

#flutter #android #web-development #web #dart #firebase #google #ui 

Pre-built Widgets /Utilites to Integrate Firebase Firestore In Flutter

A Convenient Collection Of Popular Icon Packs For Flutter

Icons Plus 

Icons Plus is a flutter package that provides access to multiple popular icon packs in one place, making it easier for developers to enhance the appearance of their apps with a wider range of icon choices. With this package, developers can make their apps more visually appealing by selecting from a variety of popular icon packs.

What's new in version 4.0

Here is a comprehensive list of the icon packs included in the package

Currently, the following icon packs are available, and additional icon packs will be included in the upcoming release.

Bootstrap version: 1.10.0 LICENSE

BoxIcons version: 2.1.4 LICENSE

  • Logo
  • Regular
  • Solid

EvaIcons version: 1.1.3 LICENSE

  • Fill
  • Outline

Flags

FontAwesome version: 6.3.0 LICENSE

  • Regular
  • Solid
  • Brand

HeroIcons version: 2.0.14 LICENSE

Iconsax version: 1.0 LICENSE

IonIcons version: 5.5.2 LICENSE

Logos

LineAwesome version: 1.3.0 LICENSE

OctIcons version: 17.11.1 LICENSE

PixelArtIcons version: 1.7.0 LICENSE

Bootstrap

Here's an illustration on utilizing Bootstrap icons.

bootstrap

  Icon(Bootstrap.google),
  Icon(Bootstrap.bootstrap),
  Icon(Bootstrap.git),
  Icon(Bootstrap.meta),
  Icon(Bootstrap.github),

BoxIcons

Here's an illustration on utilizing BoxIcons. To use Boxicons logo icon, use the prefix bxl; for a regular icon, use bx, and for a solid icon, use bxs.

boxicons

  Icon(BoxIcons.bxl_stripe),
  Icon(BoxIcons.bxl_firebase),
  Icon(BoxIcons.bxl_git),
  Icon(BoxIcons.bxl_github),
  Icon(BoxIcons.bxl_google),

EvaIcons

Here's an illustration on utilizing EvaIcons.

evaicons

  Icon(EvaIcons.twitter),
  Icon(EvaIcons.facebook),
  Icon(EvaIcons.github),
  Icon(EvaIcons.google),
  Icon(EvaIcons.linkedin),

Flags

Here's an illustration on utilizing Flags.

flags

  Flag(Flags.spain),
  Flag(Flags.india),
  Flag(Flags.france),
  Flag(Flags.united_kingdom),
  Flag(Flags.united_states_of_america),

FontAwesome

Here's an illustration on utilizing FontAwesome icons.

fontawesome

  Icon(FontAwesome.golang),
  Icon(FontAwesome.google),
  Icon(FontAwesome.google_drive),
  Icon(FontAwesome.android),
  Icon(FontAwesome.angular),

HeroIcons

Here's an illustration on utilizing HeroIcons.

heroicons

  Icon(HeroIcons.cake),
  Icon(HeroIcons.fire),
  Icon(HeroIcons.command_line),
  Icon(HeroIcons.cloud),
  Icon(HeroIcons.code_bracket),

Iconsax

Here's an illustration on utilizing Iconsax icons.

iconsax

  Icon(Iconsax.cloud),
  Icon(Iconsax.data),
  Icon(Iconsax.heart),
  Icon(Iconsax.lovely),
  Icon(Iconsax.mouse),

IonIcons

Here's an illustration on utilizing IonIcons.

ionicons

  Icon(IonIcons.logo_google),
  Icon(IonIcons.logo_nodejs),
  Icon(IonIcons.logo_android),
  Icon(IonIcons.logo_angular),
  Icon(IonIcons.logo_firebase),

LineAwesome

Here's an illustration on utilizing LineAwesome icons.

lineawsome

  Icon(LineAwesome.github),
  Icon(LineAwesome.google),
  Icon(LineAwesome.android),
  Icon(LineAwesome.angular),
  Icon(LineAwesome.apple),

Logos

Here's an illustration on utilizing Logos.

logos

  Logo(Logos.google),
  Logo(Logos.android),
  Logo(Logos.angular),
  Logo(Logos.firebase),
  Logo(Logos.flutter),

OctIcons

Here's an illustration on utilizing OctIcons.

octicons

  Icon(OctIcons.git_branch_24),
  Icon(OctIcons.git_commit_24),
  Icon(OctIcons.git_pull_request_24),
  Icon(OctIcons.verified_24),
  Icon(OctIcons.git_merge_24),

PixelArtIcons

Here's an illustration on utilizing PixelArtIcons.

pixelarticons

  Icon(PixelArtIcons.message),
  Icon(PixelArtIcons.android),
  Icon(PixelArtIcons.cloud),
  Icon(PixelArtIcons.code),
  Icon(PixelArtIcons.dollar),

Report bugs or issues

You are welcome to open a ticket on github if any problems arise. New ideas are always welcome.

Contributors

rohit-chouhan

Copyright and License

Copyright © 2022 Rahul Chouhan. Licensed under the MIT LICENSE.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add icons_plus

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  icons_plus: ^4.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:icons_plus/icons_plus.dart';

example/example.md

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

void main() => runApp(MaterialApp(home: Home()));

class Home extends StatelessWidget {
  const Home({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: ListView(
        children: [
          Icon(Bootstrap.bootstrap),
          Icon(BoxIcons.bxl_google),
          Icon(BoxIcons.bxl_github),
          Icon(BoxIcons.bxs_mobile),
          Icon(EvaIcons.twitter),
          Flag(Flags.united_states_of_america),
          Icon(FontAwesome.microsoft),
          Icon(HeroIcons.heart),
          Icon(Iconsax.google_play),
          Icon(IonIcons.logo_android),
          Icon(LineAwesome.youtube),
          Logo(Logos.firebase),
          Icon(PixelArtIcons.git_merge),
          Icon(OctIcons.git_compare_24),
        ],
      ),
    );
  }
}

Download details:

Author: rahulchouhan.me

Source: https://github.com/chouhan-rahul/icons_plus

#flutter #android #web-development #web #ui #image 

A Convenient Collection Of Popular Icon Packs For Flutter
Royce  Reinger

Royce Reinger

1686028500

Create UIs for Your Machine Learning Model in Python in 3 Minutes

Build & share delightful machine learning apps easily


Gradio: Build Machine Learning Web Apps — in Python

Gradio is an open-source Python library that is used to build machine learning and data science demos and web applications.

With Gradio, you can quickly create a beautiful user interface around your machine learning models or data science workflow and let people "try it out" by dragging-and-dropping in their own images, pasting text, recording their own voice, and interacting with your demo, all through the browser.

Interface montage

Gradio is useful for:

Demoing your machine learning models for clients/collaborators/users/students.

Deploying your models quickly with automatic shareable links and getting feedback on model performance.

Debugging your model interactively during development using built-in manipulation and interpretation tools.

Quickstart

Prerequisite: Gradio requires Python 3.7 or higher, that's all!

What Does Gradio Do?

One of the best ways to share your machine learning model, API, or data science workflow with others is to create an interactive app that allows your users or colleagues to try out the demo in their browsers.

Gradio allows you to build demos and share them, all in Python. And usually in just a few lines of code! So let's get started.

Hello, World

To get Gradio running with a simple "Hello, World" example, follow these three steps:

1. Install Gradio using pip:

pip install gradio

2. Run the code below as a Python script or in a Jupyter Notebook (or Google Colab):

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(fn=greet, inputs="text", outputs="text")
demo.launch()

3. The demo below will appear automatically within the Jupyter Notebook, or pop in a browser on http://localhost:7860 if running from a script:

hello_world demo

The Interface Class

You'll notice that in order to make the demo, we created a gradio.Interface. This Interface class can wrap any Python function with a user interface. In the example above, we saw a simple text-based function, but the function could be anything from music generator to a tax calculator to the prediction function of a pretrained machine learning model.

The core Interface class is initialized with three required parameters:

  • fn: the function to wrap a UI around
  • inputs: which component(s) to use for the input (e.g. "text", "image" or "audio")
  • outputs: which component(s) to use for the output (e.g. "text", "image" or "label")

Let's take a closer look at these components used to provide input and output.

Components Attributes

We saw some simple Textbox components in the previous examples, but what if you want to change how the UI components look or behave?

Let's say you want to customize the input text field — for example, you wanted it to be larger and have a text placeholder. If we use the actual class for Textbox instead of using the string shortcut, you have access to much more customizability through component attributes.

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

demo = gr.Interface(
    fn=greet,
    inputs=gr.Textbox(lines=2, placeholder="Name Here..."),
    outputs="text",
)
demo.launch()

hello_world_2 demo

Multiple Input and Output Components

Suppose you had a more complex function, with multiple inputs and outputs. In the example below, we define a function that takes a string, boolean, and number, and returns a string and number. Take a look how you pass a list of input and output components.

import gradio as gr

def greet(name, is_morning, temperature):
    salutation = "Good morning" if is_morning else "Good evening"
    greeting = f"{salutation} {name}. It is {temperature} degrees today"
    celsius = (temperature - 32) * 5 / 9
    return greeting, round(celsius, 2)

demo = gr.Interface(
    fn=greet,
    inputs=["text", "checkbox", gr.Slider(0, 100)],
    outputs=["text", "number"],
)
demo.launch()

hello_world_3 demo

You simply wrap the components in a list. Each component in the inputs list corresponds to one of the parameters of the function, in order. Each component in the outputs list corresponds to one of the values returned by the function, again in order.

An Image Example

Gradio supports many types of components, such as Image, DataFrame, Video, or Label. Let's try an image-to-image function to get a feel for these!

import numpy as np
import gradio as gr

def sepia(input_img):
    sepia_filter = np.array([
        [0.393, 0.769, 0.189], 
        [0.349, 0.686, 0.168], 
        [0.272, 0.534, 0.131]
    ])
    sepia_img = input_img.dot(sepia_filter.T)
    sepia_img /= sepia_img.max()
    return sepia_img

demo = gr.Interface(sepia, gr.Image(shape=(200, 200)), "image")
demo.launch()

sepia_filter demo

When using the Image component as input, your function will receive a NumPy array with the shape (width, height, 3), where the last dimension represents the RGB values. We'll return an image as well in the form of a NumPy array.

You can also set the datatype used by the component with the type= keyword argument. For example, if you wanted your function to take a file path to an image instead of a NumPy array, the input Image component could be written as:

gr.Image(type="filepath", shape=...)

Also note that our input Image component comes with an edit button 🖉, which allows for cropping and zooming into images. Manipulating images in this way can help reveal biases or hidden flaws in a machine learning model!

You can read more about the many components and how to use them in the Gradio docs.

Blocks: More Flexibility and Control

Gradio offers two classes to build apps:

1. Interface, that provides a high-level abstraction for creating demos that we've been discussing so far.

2. Blocks, a low-level API for designing web apps with more flexible layouts and data flows. Blocks allows you to do things like feature multiple data flows and demos, control where components appear on the page, handle complex data flows (e.g. outputs can serve as inputs to other functions), and update properties/visibility of components based on user interaction — still all in Python. If this customizability is what you need, try Blocks instead!

Hello, Blocks

Let's take a look at a simple example. Note how the API here differs from Interface.

import gradio as gr

def greet(name):
    return "Hello " + name + "!"

with gr.Blocks() as demo:
    name = gr.Textbox(label="Name")
    output = gr.Textbox(label="Output Box")
    greet_btn = gr.Button("Greet")
    greet_btn.click(fn=greet, inputs=name, outputs=output)

demo.launch()

hello_blocks demo

Things to note:

  • Blocks are made with a with clause, and any component created inside this clause is automatically added to the app.
  • Components appear vertically in the app in the order they are created. (Later we will cover customizing layouts!)
  • A Button was created, and then a click event-listener was added to this button. The API for this should look familiar! Like an Interface, the click method takes a Python function, input components, and output components.

More Complexity

Here's an app to give you a taste of what's possible with Blocks:

import numpy as np
import gradio as gr

def flip_text(x):
    return x[::-1]

def flip_image(x):
    return np.fliplr(x)

with gr.Blocks() as demo:
    gr.Markdown("Flip text or image files using this demo.")
    with gr.Tabs():
        with gr.TabItem("Flip Text"):
            text_input = gr.Textbox()
            text_output = gr.Textbox()
            text_button = gr.Button("Flip")
        with gr.TabItem("Flip Image"):
            with gr.Row():
                image_input = gr.Image()
                image_output = gr.Image()
            image_button = gr.Button("Flip")
    
    text_button.click(flip_text, inputs=text_input, outputs=text_output)
    image_button.click(flip_image, inputs=image_input, outputs=image_output)
    
demo.launch()

blocks_flipper demo

A lot more going on here! We'll cover how to create complex Blocks apps like this in the building with blocks section for you.

Congrats, you're now familiar with the basics of Gradio! 🥳 Go to our next guide to learn more about the key features of Gradio.

Citation

Also check out the paper Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild, ICML HILL 2019, and please cite it if you use Gradio in your work.

@article{abid2019gradio,
  title = {Gradio: Hassle-Free Sharing and Testing of ML Models in the Wild},
  author = {Abid, Abubakar and Abdalla, Ali and Abid, Ali and Khan, Dawood and Alfozan, Abdulrahman and Zou, James},
  journal = {arXiv preprint arXiv:1906.02569},
  year = {2019},
}

See Also


Website | Documentation | Guides | Getting Started | Examples


Download Details:

Author: Gradio-app
Source Code: https://github.com/gradio-app/gradio 
License: Apache-2.0 license

#machinelearning #python #datascience #ui #deeplearning #datavisualization 

Create UIs for Your Machine Learning Model in Python in 3 Minutes

A Flutter Package That You Can Use Via The Image.asset Method

country_icons

A dart package with many country flag icons

Getting Started

This package provides country icons as png and svg.

Icons as png

You can use png icons via new Image.asset('icons/flags/png/xx.png', package: 'country_icons');

Icons as svg

You can use svg icons via new Image.asset('icons/flags/svg/xx.svg', package: 'country_icons');

Credits

Flags are used from hjnilsson

Repo: https://github.com/hjnilsson/country-flags Homepage: http://hjnilsson.github.io/country-flags

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add country_icons

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  country_icons: ^2.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:country_icons/country_icons.dart';

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
   return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GridView.count(
        primary: false,
        padding: const EdgeInsets.all(20.0),
        crossAxisSpacing: 10.0,
        crossAxisCount: 2,
        children: <Widget>[
          Image.asset('icons/flags/png/de.png', package: 'country_icons'),
          Image.asset('icons/flags/png/gb.png', package: 'country_icons'),
          Image.asset('icons/flags/png/fr.png', package: 'country_icons'),
          Image.asset('icons/flags/png/es.png', package: 'country_icons'),
          Image.asset('icons/flags/png/it.png', package: 'country_icons'),
          Image.asset('icons/flags/png/eu.png', package: 'country_icons'),

          Image.asset('icons/flags/png/2.5x/de.png', package: 'country_icons'),
          Image.asset('icons/flags/png/2.5x/gb.png', package: 'country_icons'),
          Image.asset('icons/flags/png/2.5x/fr.png', package: 'country_icons'),
          Image.asset('icons/flags/png/2.5x/es.png', package: 'country_icons'),
          Image.asset('icons/flags/png/2.5x/it.png', package: 'country_icons'),
          Image.asset('icons/flags/png/2.5x/eu.png', package: 'country_icons'),

          SvgPicture.asset('icons/flags/svg/de.svg', package: 'country_icons'),
          SvgPicture.asset('icons/flags/svg/gb.svg', package: 'country_icons'),
          SvgPicture.asset('icons/flags/svg/fr.svg', package: 'country_icons'),
          SvgPicture.asset('icons/flags/svg/es.svg', package: 'country_icons'),
          SvgPicture.asset('icons/flags/svg/it.svg', package: 'country_icons'),
          SvgPicture.asset('icons/flags/svg/eu.svg', package: 'country_icons'),
        ],
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Download details:

Author: bytepark

Source: https://github.com/bytepark/country_icons

#flutter #android #web-development #web #location #ui

A Flutter Package That You Can Use Via The Image.asset Method

Get Child`s Rectangle information After Rendered In Flutter

A widget provide a simple way to get child's rectangle information after rendered.

Usage

To use this plugin, add rect_getter as a dependency in your pubspec.yaml file.

Example

// Import package
import 'package:rect_getter/rect_getter.dart';

// Instantiate it

var globalKey = RectGetter.createGlobalKey();
var rectGetter = RectGetter(
    key: globalKey,
    child: _child,
);

or

var rectGetter = RectGetter.defaultKey(
    child: _child,
);


// and add it to your layout .

// then you can get rect by

Rect rect = rectGetter.getRect();

or

Rect rect = RectGetter.getRectFromKey(globalKey);


Read More : 利用RectGetter组件获取控件位置尺寸实现的几个高级效果和功能

Getting Started

For help getting started with Flutter, view our online documentation.

For help on editing package code, view the documentation.

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add rect_getter

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  rect_getter: ^1.1.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:rect_getter/rect_getter.dart';

example/lib/main.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'dart:math' show Random;

import 'package:rect_getter/rect_getter.dart';

void main() => runApp(MyApp());

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

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, required this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Random random = Random();

  var _counter = 21;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 3,
        ),
        itemCount: _counter,
        itemBuilder: (BuildContext context, int index) {
          if (index == _counter - 1) {
            Timer(Duration.zero, () {
              setState(() {
                _counter += 21;
              });
            });
          }

          var globalKey = RectGetter.createGlobalKey();
          return FittedBox(
            child: RectGetter(
              key: globalKey,
              child: GestureDetector(
                onTap: () {
                  var rect = RectGetter.getRectFromKey(globalKey);
                  ScaffoldMessenger.of(context).showSnackBar(SnackBar(content: Text('$index : ${rect.toString()}')));
                },
                child: Container(
                  color: Colors.primaries[index % Colors.primaries.length],
                  width: random.nextInt(100) + 100.0,
                  height: random.nextInt(150) + 150.0,
                  child: Center(
                    child: Text('$index'),
                  ),
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

Download details:

Author: debuggerx.com

Source: https://github.com/debuggerx01/rect_getter

#flutter #ui #plugin #android #ios #web-development #web 

Get Child`s Rectangle information After Rendered In Flutter

Fade / Size Transition Between Widgets Of Different Heights In Flutter

This allows you to:

  1. Do a fade and size transition between two widgets.
  2. Show and hide a widget, by resizing it vertically while fading.

Size and Fade

The AnimatedSizeAndFade widget does a fade and size transition between a "new" widget and an "old" widget previously set as a child. The "old" and the "new" children must have the same width, but can have different heights, and you don't need to know their sizes in advance.

You can also define a duration and curve for both the fade and the size, separately.

Important: If the "new" child is the same widget type as the "old" child, but with different parameters, then AnimatedSizeAndFade will NOT do a transition between them, since as far as the framework is concerned, they are the same widget, and the existing widget can be updated with the new parameters. To force the transition to occur, set a Key (typically a ValueKey taking any widget data that would change the visual appearance of the widget) on each child widget that you wish to be considered unique.

Example:

bool toggle=true;
Widget widget1 = ...;
Widget widget2 = ...;

AnimatedSizeAndFade(
   child: toggle ? widget1 : widget2
);

Show and Hide

The AnimatedSizeAndFade.showHide constructor may be used to show/hide a widget, by resizing it vertically while fading.

Example:

bool toggle=true;
Widget widget = ...;    

AnimatedSizeAndFade.showHide(
   show: toggle,
   child: widget,
);

How does it compare to other similar widgets?

With AnimatedCrossFade you must keep both the firstChild and secondChild, which is not necessary with AnimatedSizeAndFade.

With AnimatedSwitcher you may simply change its child, but then it only animates the fade, not the size.

AnimatedContainer also doesn't work unless you know the size of the children in advance.


Note: See the StackOverflow question that prompted this widget development.


The Flutter packages I've authored:

My Medium Articles:

My article in the official Flutter documentation:


Marcelo Glasberg:
https://github.com/marcglasberg
https://twitter.com/glasbergmarcelo
https://stackoverflow.com/users/3411681/marcg
https://medium.com/@marcglasberg

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add animated_size_and_fade

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  animated_size_and_fade: ^3.0.1

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:animated_size_and_fade/animated_size_and_fade.dart';

example/lib/main.dart

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

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  late bool toggle;

  @override
  void initState() {
    super.initState();
    toggle = false;
  }

  @override
  Widget build(BuildContext context) {
    var toggleButton = Padding(
      padding: const EdgeInsets.all(8.0),
      child: MaterialButton(
        child: const Text("Toggle"),
        color: Colors.grey,
        onPressed: () {
          setState(() {
            toggle = !toggle;
          });
        },
      ),
    );

    var widget1 = Container(
      key: ValueKey("first"),
      color: Colors.blue,
      width: 200.0,
      child: const Text(
        "And I promise you I'll never desert you again because after 'Salome' "
        "we'll make another picture and another picture. "
        "You see, this is my life! "
        "It always will be! Nothing else! "
        "Just us, the cameras, and those wonderful people out there in the dark!...",
      ),
    );

    var widget2 = Container(
      key: ValueKey("second"),
      color: Colors.red,
      width: 200.0,
      child: const Text(
        "I am ready for my closeup.",
      ),
    );

    return MaterialApp(
      home: Material(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(height: 100.0),
            toggleButton,
            Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                const Text("Some text above."),
                AnimatedSizeAndFade(
                  child: toggle ? widget1 : widget2,
                  fadeDuration: const Duration(milliseconds: 300),
                  sizeDuration: const Duration(milliseconds: 600),
                ),
                const Text("Some text below."),
              ],
            ),
          ],
        ),
      ),
    );
  }
}

Download details:

Author: glasberg.dev

Source: https://github.com/marcglasberg/animated_size_and_fade

#flutter #ui #android #ios #web-development 

Fade / Size Transition Between Widgets Of Different Heights In Flutter

A Flutter Plugin for Controlling Screen Brightness

A Plugin for controlling screen brightness with application life cycle reset implemented.

This plugin only changes application brightness not system brightness. So no permission is needed for this plugin.

Getting Started

Install

Add the following lines in your pubspec.yaml file

  screen_brightness: ^latest_version

API

System brightness

Future<double> get systemBrightness async {
  try {
    return await ScreenBrightness().system;
  } catch (e) {
    print(e);
    throw 'Failed to get system brightness';
  }
}

Current brightness

Future<double> get currentBrightness async {
  try {
    return await ScreenBrightness().current;
  } catch (e) {
    print(e);
    throw 'Failed to get current brightness';
  }
}

Set brightness

Future<void> setBrightness(double brightness) async {
  try {
    await ScreenBrightness().setScreenBrightness(brightness);
  } catch (e) {
    print(e);
    throw 'Failed to set brightness';
  }
}

Reset brightness

Future<void> resetBrightness() async {
  try {
    await ScreenBrightness().resetScreenBrightness();
  } catch (e) {
    print(e);
    throw 'Failed to reset brightness';
  }
}

Current brightness changed stream

@override
Widget build(BuildContext context) {
  return StreamBuilder<double>(
    stream: ScreenBrightness().onCurrentBrightnessChanged,
    builder: (context, snapshot) {
      double changedBrightness = currentBrightness;
      if (snapshot.hasData) {
        changedBrightness = snapshot.data!;
      }
        
      return Text('current brightness $changedBrightness');
    },
  );
}

Has changed

@override
Widget build(BuildContext context) {
  return FutureBuilder<bool>(
    future: ScreenBrightness().hasChanged,
    builder: (context, snapshot) {
      return Text(
          'Brightness has changed via plugin: ${snapshot.data}');
    },
  );
}

Auto reset (iOS only) (experiment feature things maybe weird)

bool isAutoReset = true;

Future<void> getAutoResetSetting() async {
  if (!Platform.isIOS) {
    return;
  }

  final _isAutoReset = await ScreenBrightness().isAutoReset;
  setState(() {
    isAutoReset = _isAutoReset;
  });
}

@override
Widget build(BuildContext context) {
  return Switch(
    value: isAutoReset,
    onChanged: !Platform.isIOS
        ? null
        : (value) async {
      await ScreenBrightness().setAutoReset(value);
      await getAutoResetSetting();
    },
  );
}

Usage

  • DON'T use didChangeAppLifecycleState to set or reset brightness because this plugin already implemented this function.
  • You may also use this plugin with wakelock to prevent screen sleep

Maintainer

Jack Liu

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add screen_brightness

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  screen_brightness: ^0.2.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:screen_brightness/screen_brightness.dart';

example/lib/main.dart

import 'dart:io';

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

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

class MyApp extends StatelessWidget {
  static final RouteObserver<Route> routeObserver = RouteObserver<Route>();

  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: const HomePage(),
      onGenerateRoute: (settings) {
        late final Widget page;
        switch (settings.name) {
          case HomePage.routeName:
            page = const HomePage();
            break;

          case ControllerPage.routeName:
            page = const ControllerPage();
            break;

          case RouteAwarePage.routeName:
            page = const RouteAwarePage();
            break;

          case BlankPage.routeName:
            page = const BlankPage();
            break;

          case SettingPage.routeName:
            page = const SettingPage();
            break;

          default:
            throw UnimplementedError('page name not found');
        }

        return MaterialPageRoute(
          builder: (context) => page,
          settings: settings,
        );
      },
      navigatorObservers: [
        routeObserver,
      ],
    );
  }
}

class HomePage extends StatelessWidget {
  static const routeName = '/home';

  const HomePage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Screen brightness example'),
      ),
      body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: [
            FutureBuilder<double>(
              future: ScreenBrightness().current,
              builder: (context, snapshot) {
                double currentBrightness = 0;
                if (snapshot.hasData) {
                  currentBrightness = snapshot.data!;
                }

                return StreamBuilder<double>(
                  stream: ScreenBrightness().onCurrentBrightnessChanged,
                  builder: (context, snapshot) {
                    double changedBrightness = currentBrightness;
                    if (snapshot.hasData) {
                      changedBrightness = snapshot.data!;
                    }

                    return Text('current brightness $changedBrightness');
                  },
                );
              },
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(ControllerPage.routeName),
              child: const Text('Controller example page'),
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(RouteAwarePage.routeName),
              child: const Text('Route aware example page'),
            ),
            ElevatedButton(
              onPressed: () =>
                  Navigator.of(context).pushNamed(SettingPage.routeName),
              child: const Text('Setting page'),
            ),
          ],
        ),
      ),
    );
  }
}

class ControllerPage extends StatefulWidget {
  static const routeName = '/controller';

  const ControllerPage({Key? key}) : super(key: key);

  @override
  State<ControllerPage> createState() => _ControllerPageState();
}

class _ControllerPageState extends State<ControllerPage> {
  Future<void> setBrightness(double brightness) async {
    try {
      await ScreenBrightness().setScreenBrightness(brightness);
    } catch (e) {
      debugPrint(e.toString());
      throw 'Failed to set brightness';
    }
  }

  Future<void> resetBrightness() async {
    try {
      await ScreenBrightness().resetScreenBrightness();
    } catch (e) {
      debugPrint(e.toString());
      throw 'Failed to reset brightness';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Controller'),
      ),
      body: Center(
        child: FutureBuilder<double>(
          future: ScreenBrightness().current,
          builder: (context, snapshot) {
            double currentBrightness = 0;
            if (snapshot.hasData) {
              currentBrightness = snapshot.data!;
            }

            return StreamBuilder<double>(
              stream: ScreenBrightness().onCurrentBrightnessChanged,
              builder: (context, snapshot) {
                double changedBrightness = currentBrightness;
                if (snapshot.hasData) {
                  changedBrightness = snapshot.data!;
                }

                return Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    FutureBuilder<bool>(
                      future: ScreenBrightness().hasChanged,
                      builder: (context, snapshot) {
                        return Text(
                            'Brightness has changed via plugin: ${snapshot.data}');
                      },
                    ),
                    Text('Current brightness: $changedBrightness'),
                    Slider.adaptive(
                      value: changedBrightness,
                      onChanged: (value) {
                        setBrightness(value);
                      },
                    ),
                    ElevatedButton(
                      onPressed: () {
                        resetBrightness();
                      },
                      child: const Text('reset brightness'),
                    ),
                  ],
                );
              },
            );
          },
        ),
      ),
    );
  }
}

class RouteAwarePage extends StatefulWidget {
  static const routeName = '/routeAware';

  const RouteAwarePage({Key? key}) : super(key: key);

  @override
  _RouteAwarePageState createState() => _RouteAwarePageState();
}

class _RouteAwarePageState extends State<RouteAwarePage> with RouteAware {
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    MyApp.routeObserver.subscribe(this, ModalRoute.of(context)!);
  }

  @override
  void dispose() {
    MyApp.routeObserver.unsubscribe(this);
    super.dispose();
  }

  @override
  void didPush() {
    super.didPush();
    ScreenBrightness().setScreenBrightness(0.7);
  }

  @override
  void didPushNext() {
    super.didPushNext();
    ScreenBrightness().resetScreenBrightness();
  }

  @override
  void didPop() {
    super.didPop();
    ScreenBrightness().resetScreenBrightness();
  }

  @override
  void didPopNext() {
    super.didPopNext();
    ScreenBrightness().setScreenBrightness(0.7);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Route aware'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () => Navigator.of(context).pushNamed(BlankPage.routeName),
          child: const Text('Next page'),
        ),
      ),
    );
  }
}

class BlankPage extends StatelessWidget {
  static const routeName = '/blankPage';

  const BlankPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Blank'),
      ),
    );
  }
}

class SettingPage extends StatefulWidget {
  static const routeName = '/setting';

  const SettingPage({Key? key}) : super(key: key);

  @override
  _SettingPageState createState() => _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  bool isAutoReset = true;

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

  Future<void> getAutoResetSetting() async {
    final _isAutoReset = await ScreenBrightness().isAutoReset;
    setState(() {
      isAutoReset = _isAutoReset;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Setting'),
      ),
      body: ListView(
        children: [
          ListTile(
            title: const Text('Auto Reset (iOS only)'),
            trailing: Switch(
              value: isAutoReset,
              onChanged:
                  Platform.isIOS || Platform.isWindows || Platform.isMacOS
                      ? (value) async {
                          await ScreenBrightness().setAutoReset(value);
                          await getAutoResetSetting();
                        }
                      : null,
            ),
          )
        ],
      ),
    );
  }
}

Download details:

Author: aaassseee

Source: https://github.com/aaassseee/screen_brightness/tree/master/screen_brightness

#flutter #ui #applications #mobileapp #mobile-apps #mobile #android 

A Flutter Plugin for Controlling Screen Brightness

The Development Of an Existing Package Chart for Flutter

D'Chart is the development of an existing package chart, namely community_charts_flutter.
The purpose of this pakage is simple way to use chart from community_charts_flutter.

Usage

  • Wrap Chart with Widget Size like SizedBox, Container, Aspecration etc to set root size for chart
  • Example
AspectRation(
    aspectRatio: 16/9,
    child: DChartTime(),
),

SizedBox(
    width: 240,
    height: 200,
    child: DChartTime(),
)

Bar

Bar Image

dchart_bar1 dchart_bar2 dchart_bar3

Bar Example

DChartBar(
    data: [
        {
            'id': 'Bar',
            'data': [
                {'domain': '2020', 'measure': 3},
                {'domain': '2021', 'measure': 4},
                {'domain': '2022', 'measure': 6},
                {'domain': '2023', 'measure': 0.3},
            ],
        },
    ],
    domainLabelPaddingToAxisLine: 16,
    axisLineTick: 2,
    axisLinePointTick: 2,
    axisLinePointWidth: 10,
    axisLineColor: Colors.green,
    measureLabelPaddingToAxisLine: 16,
    barColor: (barData, index, id) => Colors.green,
    showBarValue: true,
),


 

Line

Line Image

dchart_line1 dchart_line2

Line Example

DChartLine(
    data: [
        {
            'id': 'Line',
            'data': [
                {'domain': 0, 'measure': 4.1},
                {'domain': 2, 'measure': 4},
                {'domain': 3, 'measure': 6},
                {'domain': 4, 'measure': 1},
            ],
        },
    ],
    lineColor: (lineData, index, id) => Colors.amber,
),


 

Pie

Pie Image

dchart_pie1

Pie Example

DChartPie(
    data: [
        {'domain': 'Flutter', 'measure': 28},
        {'domain': 'React Native', 'measure': 27},
        {'domain': 'Ionic', 'measure': 20},
        {'domain': 'Cordova', 'measure': 15},
    ],
    fillColor: (pieData, index) => Colors.purple,
),


 

Donut

Donut Image

dchart_pie2

Donut Example

DChartPie(
    data: [
        {'domain': 'Flutter', 'measure': 28},
        {'domain': 'React Native', 'measure': 27},
        {'domain': 'Ionic', 'measure': 20},
        {'domain': 'Cordova', 'measure': 15},
    ],
    fillColor: (pieData, index) => Colors.purple,
    donutWidth: 30,
    labelColor: Colors.white,
),


 

Gauge

Gauge Image

dchart_gauge

Gauge Example

DChartGauge(
    data: [
        {'domain': 'Off', 'measure': 30},
        {'domain': 'Warm', 'measure': 30},
        {'domain': 'Hot', 'measure': 30},
    ],
    fillColor: (pieData, index) {
        switch (pieData['domain']) {
            case 'Off':
            return Colors.green;
            case 'Warm':
            return Colors.orange;
            default:
            return Colors.red;
        }
    },
    showLabelLine: false,
    pieLabel: (pieData, index) {
        return "${pieData['domain']}";
    },
    labelPosition: PieLabelPosition.inside,
    labelPadding: 0,
    labelColor: Colors.white,
),


 

Bar Custom

this is not depend on community_charts_flutter

Bar Custom Image

dchart_bar_custom1 dchart_bar_custom2

Bar Custom Example

// example 1
AspectRatio(
    aspectRatio: 16 / 9,
    child: DChartBarCustom(
        showDomainLine: true,
        showMeasureLine: true,
        showDomainLabel: true,
        showMeasureLabel: true,
        spaceBetweenItem: 8,
        listData: [
            DChartBarDataCustom(
                value: 13,
                label: 'Jan',
                color: Colors.blue,
            ),
            DChartBarDataCustom(value: 20, label: 'Feb'),
            DChartBarDataCustom(value: 30, label: 'Mar'),
            DChartBarDataCustom(value: 40, label: 'Apr'),
            DChartBarDataCustom(value: 25, label: 'Mei'),
        ],
    ),
),

// example 2
List ranking = [
    {'class': 'A', 'total': 23},
    {'class': 'B', 'total': 14},
    {'class': 'C', 'total': 8},
    {'class': 'D', 'total': 7},
    {'class': 'E', 'total': 21},
];
DChartBarCustom(
    loadingDuration: const Duration(milliseconds: 1500),
    showLoading: true,
    valueAlign: Alignment.topCenter,
    showDomainLine: true,
    showDomainLabel: true,
    showMeasureLine: true,
    showMeasureLabel: true,
    spaceDomainLabeltoChart: 10,
    spaceMeasureLabeltoChart: 5,
    spaceDomainLinetoChart: 15,
    spaceMeasureLinetoChart: 20,
    spaceBetweenItem: 16,
    radiusBar: const BorderRadius.only(
        topLeft: Radius.circular(8),
        topRight: Radius.circular(8),
    ),
    measureLabelStyle: const TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 16,
        color: Colors.purple,
    ),
    domainLabelStyle: const TextStyle(
        fontWeight: FontWeight.bold,
        fontSize: 16,
        color: Colors.purple,
    ),
    measureLineStyle:
        const BorderSide(color: Colors.amber, width: 2),
    domainLineStyle: const BorderSide(color: Colors.red, width: 2),
    max: 25,
    listData: List.generate(ranking.length, (index) {
        Color currentColor =
            Color((Random().nextDouble() * 0xFFFFFF).toInt());
        return DChartBarDataCustom(
            onTap: () {
                print(
                '${ranking[index]['class']} => ${ranking[index]['total']}',
                );
            },
            elevation: 8,
            value: ranking[index]['total'].toDouble(),
            label: ranking[index]['class'],
            color: currentColor.withOpacity(1),
            splashColor: Colors.blue,
            showValue: ranking[index]['class'] == 'C' ? false : true,
            valueStyle: ranking[index]['class'] == 'A'
                ? const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                    color: Colors.black,
                    )
                : const TextStyle(
                    fontWeight: FontWeight.bold,
                    fontSize: 16,
                    color: Colors.white,
                    ),
            labelCustom: ranking[index]['class'] == 'B'
                ? Transform.rotate(
                    angle: 5.5,
                    child: const Text('Bagus'),
                    )
                : null,
            valueCustom: ranking[index]['total'] > 20
                ? Align(
                    alignment: Alignment.center,
                    child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                        Container(
                            padding: const EdgeInsets.all(4),
                            decoration: BoxDecoration(
                            border: Border.all(width: 2),
                            shape: BoxShape.circle,
                            ),
                            child: Text(
                            '${ranking[index]['total']}',
                            style: const TextStyle(
                                fontSize: 11,
                                color: Colors.red,
                                fontWeight: FontWeight.w900,
                            ),
                            ),
                        ),
                        const Text(
                            '😄',
                            style: TextStyle(fontSize: 20),
                        ),
                        ],
                    ),
                    )
                : null,
            valueTooltip: '${ranking[index]['total']} Student',
        );
    }),
),


 

Time

Chart for Time Series, it can be group and custom render chart view
Render type:

  1. DRenderLine
  2. DRenderBar
  3. DRenderTargetLine
  4. DRenderPoint

Time Image

dchart_bar1 dchart_bar2 dchart_bar3 dchart_bar3

Time Example

DChartTime(
    chartRender: DRenderLine(),
    measureLabel: (value) => '${value}k',
    domainLabel: (dateTime) {
        // [DateFormat] from intl package
        return DateFormat('d MMM yy').format(dateTime!);
    },
    groupData: [
        DChartTimeGroup(
            id: 'Keyboard',
            color: Colors.blue,
            data: [
                DChartTimeData(time: DateTime(2023, 2, 1), value: 29),
                DChartTimeData(time: DateTime(2023, 2, 2), value: 73),
                DChartTimeData(time: DateTime(2023, 2, 4), value: 23),
                DChartTimeData(time: DateTime(2023, 2, 8), value: 56),
                DChartTimeData(time: DateTime(2023, 2, 9), value: 32),
                DChartTimeData(time: DateTime(2023, 2, 10), value: 21),
                DChartTimeData(time: DateTime(2023, 2, 12), value: 76),
                DChartTimeData(time: DateTime(2023, 2, 18), value: 91),
                DChartTimeData(time: DateTime(2023, 2, 20), value: 17),
            ],
        ),
    ],
),


 

Scatter

Chart for Scatter Plot/Point Series, it can be group.

Scatter Image

dchart_scatter dchart_scatter

Scatter Example

final group1 = [
    DChartScatterData(
        domain: 1,
        measure: 23,
        size: 10,
        startPlot: DPlot(2, 10),
        type: SymbolType.rect,
    ),
    DChartScatterData(
        domain: 2,
        measure: 12,
        type: SymbolType.circle,
    ),
    DChartScatterData(domain: 3, measure: 19),
];
final group2 = [
    DChartScatterData(
        domain: 1,
        measure: 15,
        type: SymbolType.triangle,
    ),
    DChartScatterData(
        domain: 3, measure: 25, type: SymbolType.triangle, size: 15),
    DChartScatterData(domain: 5, measure: 7),
];

DChartScatter(
    trackType: TrackType.rectangle,
    borderWidth: (group, data, index) => 2,
    borderColor: (random, group, data) => Colors.red.withOpacity(0.8),
    groupData: [
        DChartScatterGroup(
            id: 'id',
            data: group1,
            color: Colors.amber,
        ),
        DChartScatterGroup(
            id: 'id2',
            data: group2,
            color: Colors.purple,
        ),
    ],
),


 

Single Bar

This chart is devoted to making a comparison bar and progress bar display.

Single Bar Image

dchart_scatter

Single Bar Example

DChartSingleBar(
    forgroundColor: Colors.green,
    value: 30,
    max: 80,
),

Other

Support me for more feature & packages Donate

Check my app : Visit

Check My Tutorial & Course : Watch

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add d_chart

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  d_chart: ^2.2.11

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:d_chart/d_chart.dart';

example/lib/main.dart

import 'dart:math';

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Home(),
    );
  }
}

class Home extends StatelessWidget {
  final List ranking = [
    {'class': 'A', 'total': 23},
    {'class': 'B', 'total': 14},
    {'class': 'C', 'total': 8},
    {'class': 'D', 'total': 7},
    {'class': 'E', 'total': 21},
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('D\'Chart')),
      backgroundColor: Colors.white,
      body: SingleChildScrollView(
        child: Column(
          children: [
            ListTile(
              title: Text('Bar Chart'),
              tileColor: Colors.green[200],
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartBar(
                  data: [
                    {
                      'id': 'Bar',
                      'data': [
                        {'domain': '2020', 'measure': 3},
                        {'domain': '2021', 'measure': 4},
                        {'domain': '2022', 'measure': 6},
                        {'domain': '2023', 'measure': 0.3},
                      ],
                    },
                  ],
                  domainLabelPaddingToAxisLine: 16,
                  axisLineTick: 2,
                  axisLinePointTick: 2,
                  axisLinePointWidth: 10,
                  axisLineColor: Colors.green,
                  measureLabelPaddingToAxisLine: 16,
                  barColor: (barData, index, id) => Colors.green,
                  showBarValue: true,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartBar(
                  data: [
                    {
                      'id': 'Bar',
                      'data': [
                        {'domain': '2020', 'measure': 3},
                        {'domain': '2021', 'measure': 4},
                        {'domain': '2022', 'measure': 6},
                        {'domain': '2023', 'measure': 1.3},
                      ],
                    },
                  ],
                  domainLabelPaddingToAxisLine: 16,
                  axisLineColor: Colors.green,
                  measureLabelPaddingToAxisLine: 16,
                  barColor: (barData, index, id) => Colors.green,
                  verticalDirection: false,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartBar(
                  data: [
                    {
                      'id': 'Bar',
                      'data': [
                        {'domain': '2020', 'measure': 3},
                        {'domain': '2021', 'measure': 4},
                        {'domain': '2022', 'measure': 6},
                        {'domain': '2023', 'measure': 0.3},
                      ],
                    },
                  ],
                  domainLabelPaddingToAxisLine: 16,
                  axisLineTick: 2,
                  axisLinePointTick: 2,
                  axisLinePointWidth: 8,
                  axisLineColor: Colors.green,
                  measureLabelPaddingToAxisLine: 16,
                  barColor: (barData, index, id) => barData['measure'] >= 4
                      ? Colors.green.shade300
                      : Colors.green.shade700,
                  barValue: (barData, index) => '${barData['measure']}',
                  showBarValue: true,
                  barValuePosition: BarValuePosition.auto,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartBar(
                  data: [
                    {
                      'id': 'Bar',
                      'data': [
                        {'domain': '2020', 'measure': 3},
                        {'domain': '2021', 'measure': 4},
                        {'domain': '2022', 'measure': 6},
                        {'domain': '2023', 'measure': 0.3},
                      ],
                    },
                  ],
                  yAxisTitle: 'Year',
                  xAxisTitle: 'Sale',
                  measureMin: 0,
                  measureMax: 7,
                  minimumPaddingBetweenLabel: 1,
                  domainLabelPaddingToAxisLine: 16,
                  axisLineTick: 2,
                  axisLinePointTick: 2,
                  axisLinePointWidth: 10,
                  axisLineColor: Colors.green,
                  measureLabelPaddingToAxisLine: 16,
                  verticalDirection: false,
                  barColor: (barData, index, id) => barData['measure'] >= 4
                      ? Colors.green.shade300
                      : Colors.green.shade700,
                  barValue: (barData, index) => '${barData['measure']}%',
                  showBarValue: true,
                  barValuePosition: BarValuePosition.outside,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartBar(
                  data: [
                    {
                      'id': 'Bar 1',
                      'data': [
                        {'domain': '2019', 'measure': 3},
                        {'domain': '2020', 'measure': 3},
                        {'domain': '2021', 'measure': 4},
                        {'domain': '2022', 'measure': 6},
                        {'domain': '2023', 'measure': 0.3},
                      ],
                    },
                    {
                      'id': 'Bar 2',
                      'data': [
                        {'domain': '2020', 'measure': 4},
                        {'domain': '2021', 'measure': 5},
                        {'domain': '2022', 'measure': 2},
                        {'domain': '2023', 'measure': 1},
                        {'domain': '2024', 'measure': 2.5},
                      ],
                    },
                  ],
                  yAxisTitle: 'Year',
                  xAxisTitle: 'Sale',
                  measureMin: 0,
                  measureMax: 8,
                  minimumPaddingBetweenLabel: 1,
                  domainLabelPaddingToAxisLine: 16,
                  axisLineTick: 2,
                  axisLinePointTick: 2,
                  axisLinePointWidth: 10,
                  axisLineColor: Colors.green,
                  measureLabelPaddingToAxisLine: 16,
                  barColor: (barData, index, id) => id == 'Bar 1'
                      ? Colors.green.shade300
                      : Colors.green.shade900,
                  barValue: (barData, index) => '${barData['measure']}%',
                  showBarValue: true,
                  barValuePosition: BarValuePosition.outside,
                  verticalDirection: false,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: Row(
                children: [
                  RotatedBox(
                    quarterTurns: 1,
                    child: Text(
                      'Year',
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                        color: Colors.green,
                      ),
                    ),
                  ),
                  Expanded(
                    child: Column(
                      children: [
                        AspectRatio(
                          aspectRatio: 16 / 9,
                          child: DChartBar(
                            data: [
                              {
                                'id': 'Bar 1',
                                'data': [
                                  {'domain': '2020', 'measure': 32},
                                  {'domain': '2021', 'measure': 43},
                                  {'domain': '2022', 'measure': 29},
                                  {'domain': '2023', 'measure': 16},
                                ],
                              },
                              {
                                'id': 'Bar 2',
                                'data': [
                                  {'domain': '2020', 'measure': 24},
                                  {'domain': '2021', 'measure': 42},
                                  {'domain': '2022', 'measure': 9},
                                  {'domain': '2023', 'measure': 37},
                                ],
                              },
                              {
                                'id': 'Bar 3',
                                'data': [
                                  {'domain': '2020', 'measure': 17},
                                  {'domain': '2021', 'measure': 28},
                                  {'domain': '2022', 'measure': 12},
                                  {'domain': '2023', 'measure': 30},
                                ],
                              },
                            ],
                            minimumPaddingBetweenLabel: 1,
                            domainLabelPaddingToAxisLine: 16,
                            axisLineTick: 2,
                            axisLinePointTick: 2,
                            axisLinePointWidth: 10,
                            axisLineColor: Colors.green,
                            measureLabelPaddingToAxisLine: 16,
                            barColor: (barData, index, id) => id == 'Bar 1'
                                ? Colors.green.shade300
                                : id == 'Bar 2'
                                    ? Colors.green.shade600
                                    : Colors.green.shade900,
                            barValue: (barData, index) =>
                                '${barData['measure']}',
                            showBarValue: true,
                            barValueFontSize: 12,
                            barValuePosition: BarValuePosition.outside,
                          ),
                        ),
                        Padding(
                          padding: EdgeInsets.symmetric(vertical: 8),
                          child: Text(
                            'Year',
                            style: TextStyle(
                              fontWeight: FontWeight.bold,
                              color: Colors.green,
                            ),
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            SizedBox(height: 30),
            ListTile(
              title: Text('Line Chart'),
              tileColor: Colors.amber[200],
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartLine(
                  data: [
                    {
                      'id': 'Line',
                      'data': [
                        {'domain': 0, 'measure': 4.1},
                        {'domain': 2, 'measure': 4},
                        {'domain': 3, 'measure': 6},
                        {'domain': 4, 'measure': 1},
                      ],
                    },
                  ],
                  lineColor: (lineData, index, id) => Colors.amber,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartLine(
                  data: [
                    {
                      'id': 'Line',
                      'data': [
                        {'domain': 0, 'measure': 2.5},
                        {'domain': 2, 'measure': 4},
                        {'domain': 3, 'measure': 6},
                        {'domain': 4, 'measure': 1},
                      ],
                    },
                  ],
                  includePoints: true,
                  lineColor: (lineData, index, id) => Colors.amber,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: Row(
                children: [
                  RotatedBox(quarterTurns: 3, child: Text('Quantity')),
                  SizedBox(width: 8),
                  Expanded(
                    child: Column(
                      children: [
                        AspectRatio(
                          aspectRatio: 16 / 9,
                          child: DChartLine(
                            lineColor: (lineData, index, id) {
                              return id == 'Line 1'
                                  ? Colors.blue
                                  : Colors.amber;
                            },
                            data: [
                              {
                                'id': 'Line 1',
                                'data': [
                                  {'domain': 1, 'measure': 3},
                                  {'domain': 2, 'measure': 3},
                                  {'domain': 3, 'measure': 4},
                                  {'domain': 4, 'measure': 6},
                                  {'domain': 5, 'measure': 0.3},
                                ],
                              },
                              {
                                'id': 'Line 2',
                                'data': [
                                  {'domain': 1, 'measure': 4},
                                  {'domain': 2, 'measure': 5},
                                  {'domain': 3, 'measure': 2},
                                  {'domain': 4, 'measure': 1},
                                  {'domain': 5, 'measure': 2.5},
                                ],
                              },
                            ],
                            includePoints: true,
                          ),
                        ),
                        Text('Day'),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartLine(
                  lineColor: (lineData, index, id) {
                    return id == 'Line 1'
                        ? Colors.blue
                        : id == 'Line 2'
                            ? Colors.amber
                            : Colors.green;
                  },
                  pointColor: (lineData, index, id) {
                    return id == 'Line 1'
                        ? Colors.blue.shade900
                        : id == 'Line 2'
                            ? Colors.amber.shade900
                            : Colors.green.shade900;
                  },
                  data: [
                    {
                      'id': 'Line 1',
                      'data': [
                        {'domain': 0, 'measure': 0.5},
                        {'domain': 2, 'measure': 1},
                        {'domain': 3, 'measure': 3},
                        {'domain': 4, 'measure': 2.3},
                        {'domain': 5, 'measure': 3},
                      ],
                    },
                    {
                      'id': 'Line 2',
                      'data': [
                        {'domain': 1, 'measure': 4},
                        {'domain': 2, 'measure': 5},
                        {'domain': 3, 'measure': 4.5},
                        {'domain': 4, 'measure': 7},
                        {'domain': 5, 'measure': 8},
                      ],
                    },
                    {
                      'id': 'Line 3',
                      'data': [
                        {'domain': 1, 'measure': 8.2},
                        {'domain': 2, 'measure': 8},
                        {'domain': 3, 'measure': 9},
                        {'domain': 4, 'measure': 10},
                        {'domain': 5, 'measure': 12},
                      ],
                    },
                  ],
                  includePoints: true,
                  includeArea: true,
                ),
              ),
            ),
            ListTile(
              title: Text('Pie Chart'),
              tileColor: Colors.purple[200],
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartPie(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) => Colors.purple,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartPie(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) {
                    switch (pieData['domain']) {
                      case 'Flutter':
                        return Colors.blue;
                      case 'React Native':
                        return Colors.blueAccent;
                      case 'Ionic':
                        return Colors.lightBlue;
                      default:
                        return Colors.orange;
                    }
                  },
                  pieLabel: (pieData, index) {
                    return "${pieData['domain']}:\n${pieData['measure']}%";
                  },
                  labelPosition: PieLabelPosition.outside,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartPie(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) {
                    switch (pieData['domain']) {
                      case 'Flutter':
                        return Colors.purple.shade300;
                      case 'React Native':
                        return Colors.purple.shade500;
                      case 'Ionic':
                        return Colors.purple.shade700;
                      default:
                        return Colors.purple.shade900;
                    }
                  },
                  pieLabel: (pieData, index) {
                    return "${pieData['measure']}%";
                  },
                  labelPosition: PieLabelPosition.auto,
                  labelColor: Colors.white,
                  labelFontSize: 14,
                  labelLineColor: Colors.grey,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartPie(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) {
                    switch (pieData['domain']) {
                      case 'Flutter':
                        return Colors.purple.shade300;
                      case 'React Native':
                        return Colors.purple.shade500;
                      case 'Ionic':
                        return Colors.purple.shade700;
                      default:
                        return Colors.purple.shade900;
                    }
                  },
                  pieLabel: (pieData, index) {
                    return "${pieData['measure']}%";
                  },
                  labelPosition: PieLabelPosition.outside,
                  labelColor: Colors.deepPurple,
                  labelFontSize: 14,
                  labelLineColor: Colors.purple.shade200,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: Stack(
                  children: [
                    DChartPie(
                      data: [
                        {'domain': 'Flutter', 'measure': 28},
                        {'domain': 'React Native', 'measure': 27},
                        {'domain': 'Ionic', 'measure': 20},
                        {'domain': 'Cordova', 'measure': 15},
                      ],
                      fillColor: (pieData, index) => Colors.purple,
                      donutWidth: 30,
                      labelColor: Colors.white,
                    ),
                    Align(child: Text('Framework')),
                  ],
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartPie(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) {
                    switch (pieData['domain']) {
                      case 'Flutter':
                        return Colors.blue;
                      case 'React Native':
                        return Colors.blueAccent;
                      case 'Ionic':
                        return Colors.lightBlue;
                      default:
                        return Colors.orange;
                    }
                  },
                  pieLabel: (pieData, index) {
                    return "${pieData['domain']}:\n${pieData['measure']}%";
                  },
                  labelPosition: PieLabelPosition.outside,
                  donutWidth: 20,
                ),
              ),
            ),
            ListTile(
              title: Text('Gauge Chart'),
              tileColor: Colors.blue[200],
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartGauge(
                  data: [
                    {'domain': 'Flutter', 'measure': 28},
                    {'domain': 'React Native', 'measure': 27},
                    {'domain': 'Ionic', 'measure': 20},
                    {'domain': 'Cordova', 'measure': 15},
                  ],
                  fillColor: (pieData, index) => Colors.blue,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: DChartGauge(
                  data: [
                    {'domain': 'Off', 'measure': 30},
                    {'domain': 'Warm', 'measure': 30},
                    {'domain': 'Hot', 'measure': 30},
                  ],
                  fillColor: (pieData, index) {
                    switch (pieData['domain']) {
                      case 'Off':
                        return Colors.green;
                      case 'Warm':
                        return Colors.orange;
                      default:
                        return Colors.red;
                    }
                  },
                  showLabelLine: false,
                  pieLabel: (pieData, index) {
                    return "${pieData['domain']}";
                  },
                  labelPosition: PieLabelPosition.inside,
                  labelPadding: 0,
                  labelColor: Colors.white,
                ),
              ),
            ),
            Padding(
              padding: EdgeInsets.all(16),
              child: AspectRatio(
                aspectRatio: 16 / 9,
                child: Stack(
                  children: [
                    DChartGauge(
                      data: [
                        {'domain': 'OFF', 'measure': 1},
                        {'domain': 'N', 'measure': 1},
                        {'domain': '1', 'measure': 1},
                        {'domain': '2', 'measure': 1},
                        {'domain': '3', 'measure': 1},
                        {'domain': '4', 'measure': 1},
                        {'domain': '5', 'measure': 1},
                      ],
                      fillColor: (pieData, index) {
                        switch (pieData['domain']) {
                          case 'Off':
                            return Colors.grey.shade700;
                          case 'N':
                            return Colors.green.shade900;
                          case '3':
                            return Colors.orangeAccent;
                          default:
                            return Colors.grey[300];
                        }
                      },
                      showLabelLine: false,
                      pieLabel: (pieData, index) {
                        return "${pieData['domain']}";
                      },
                      labelPosition: PieLabelPosition.inside,
                      labelPadding: 0,
                      labelColor: Colors.white,
                    ),
                    Align(child: Text('Gassss')),
                  ],
                ),
              ),
            ),
            const SizedBox(height: 50),
            AspectRatio(
              aspectRatio: 16 / 9,
              child: DChartBarCustom(
                loadingDuration: const Duration(milliseconds: 1500),
                showLoading: true,
                valueAlign: Alignment.topCenter,
                showDomainLine: true,
                showDomainLabel: true,
                showMeasureLine: true,
                showMeasureLabel: true,
                spaceDomainLabeltoChart: 10,
                spaceMeasureLabeltoChart: 5,
                spaceDomainLinetoChart: 15,
                spaceMeasureLinetoChart: 20,
                spaceBetweenItem: 16,
                radiusBar: const BorderRadius.only(
                  topLeft: Radius.circular(8),
                  topRight: Radius.circular(8),
                ),
                measureLabelStyle: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: Colors.purple,
                ),
                domainLabelStyle: const TextStyle(
                  fontWeight: FontWeight.bold,
                  fontSize: 16,
                  color: Colors.purple,
                ),
                measureLineStyle:
                    const BorderSide(color: Colors.amber, width: 2),
                domainLineStyle: const BorderSide(color: Colors.red, width: 2),
                max: 25,
                listData: List.generate(ranking.length, (index) {
                  Color currentColor =
                      Color((Random().nextDouble() * 0xFFFFFF).toInt());
                  return DChartBarDataCustom(
                    onTap: () {
                      print(
                        '${ranking[index]['class']} => ${ranking[index]['total']}',
                      );
                    },
                    elevation: 8,
                    value: ranking[index]['total'].toDouble(),
                    label: ranking[index]['class'],
                    color: currentColor.withOpacity(1),
                    splashColor: Colors.blue,
                    showValue: ranking[index]['class'] == 'C' ? false : true,
                    valueStyle: ranking[index]['class'] == 'A'
                        ? const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                            color: Colors.black,
                          )
                        : const TextStyle(
                            fontWeight: FontWeight.bold,
                            fontSize: 16,
                            color: Colors.white,
                          ),
                    labelCustom: ranking[index]['class'] == 'B'
                        ? Transform.rotate(
                            angle: 5.5,
                            child: const Text('Bagus'),
                          )
                        : null,
                    valueCustom: ranking[index]['total'] > 20
                        ? Align(
                            alignment: Alignment.center,
                            child: Column(
                              mainAxisSize: MainAxisSize.min,
                              children: [
                                Container(
                                  padding: const EdgeInsets.all(4),
                                  decoration: BoxDecoration(
                                    border: Border.all(width: 2),
                                    shape: BoxShape.circle,
                                  ),
                                  child: Text(
                                    '${ranking[index]['total']}',
                                    style: const TextStyle(
                                      fontSize: 11,
                                      color: Colors.red,
                                      fontWeight: FontWeight.w900,
                                    ),
                                  ),
                                ),
                                const Text(
                                  '😄',
                                  style: TextStyle(fontSize: 20),
                                ),
                              ],
                            ),
                          )
                        : null,
                    valueTooltip: '${ranking[index]['total']} Student',
                  );
                }),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

/// call this to test example [DChartTime]
class DChartTimeExample extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('DChart Time Example')),
      body: ListView(
        padding: const EdgeInsets.all(20),
        children: [
          AspectRatio(
            aspectRatio: 3,
            child: DChartTime(
              fillColor: (group, data, index) => Colors.transparent,
              measureLabel: (value) => '${value}k',
              // use format intl package to custom view datetime string
              // domainLabel: (dateTime) =>
              //     DateFormat('d MMM yy').format(dateTime!),
              domainLabelStyle: const TextStyle(color: Colors.purple),
              domainLineColor: Colors.grey[800],
              chartRender: DRenderPoint(),
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 29),
                    DChartTimeData(time: DateTime(2023, 2, 2), value: 73),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 23),
                    DChartTimeData(time: DateTime(2023, 2, 8), value: 56),
                    DChartTimeData(time: DateTime(2023, 2, 9), value: 32),
                    DChartTimeData(time: DateTime(2023, 2, 10), value: 21),
                    DChartTimeData(time: DateTime(2023, 2, 12), value: 76),
                    DChartTimeData(time: DateTime(2023, 2, 18), value: 91),
                    DChartTimeData(time: DateTime(2023, 2, 20), value: 17),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 30),
          AspectRatio(
            aspectRatio: 3,
            child: DChartTime(
              chartRender: DRenderTargetLine(),
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(
                        time: DateTime(2023, 2, 1), value: 29, x: 'k'),
                    DChartTimeData(
                        time: DateTime(2023, 2, 2), value: 73, x: 'm'),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 54),
                  ],
                ),
                DChartTimeGroup(
                  id: 'Monitor',
                  color: Colors.amber,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 15),
                    DChartTimeData(time: DateTime(2023, 2, 2), value: 30),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 50),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 30),
          AspectRatio(
            aspectRatio: 3,
            child: DChartTime(
              chartRender: DRenderBar(
                // borderWidth: 10,
                barRadius: 8,
                labelSpace: 10,
                insideLabelStyle: const TextStyle(color: Colors.yellow),
                outsideLabelStyle: const TextStyle(color: Colors.purple),
                labelAlign: RBLabelAlign.end,
              ),
              // customLabelValue: (group, data, index) {
              //   String unit =
              //       data.x != null && data.x is String ? data.x.toString() : '';
              //   return '${DateFormat('d MMM').format(data.time)} :\n${data.value}$unit';
              // },
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(
                        time: DateTime(2023, 2, 1), value: 29, x: 'k'),
                    DChartTimeData(
                        time: DateTime(2023, 2, 3, 5), value: 73, x: 'm'),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 54),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 30),
          AspectRatio(
            aspectRatio: 3,
            child: DChartTime(
              chartRender: DRenderBar(
                // borderWidth: 10,
                barRadius: 16,
                labelSpace: 10,
                groupType: RBGroupType.stacked,
              ),
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 29),
                    DChartTimeData(time: DateTime(2023, 2, 3, 5), value: 73),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 54),
                  ],
                ),
                DChartTimeGroup(
                  id: 'Monitor',
                  color: Colors.amber,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 15),
                    DChartTimeData(time: DateTime(2023, 2, 1, 5), value: 30),
                    DChartTimeData(time: DateTime(2023, 2, 3), value: 50),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 30),
          AspectRatio(
            aspectRatio: 3,
            child: DChartTime(
              chartRender: DRenderLine(
                showArea: true,
                showPoint: true,
                strokeWidth: 1.5,
                pointSize: 5,
              ),
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 29),
                    DChartTimeData(time: DateTime(2023, 2, 3, 5), value: 73),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 54),
                  ],
                ),
                DChartTimeGroup(
                  id: 'Monitor',
                  color: Colors.purple,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 15),
                    DChartTimeData(time: DateTime(2023, 2, 1, 5), value: 30),
                    DChartTimeData(time: DateTime(2023, 2, 3), value: 50),
                  ],
                ),
              ],
            ),
          ),
          SizedBox(height: 30),
          AspectRatio(
            aspectRatio: 16 / 9,
            child: DChartTime(
              showLegend: true,
              legendJustify: DJustify.end,
              legendPosition: DBehaviorPosition.top,
              legendMaxColumn: 3,
              legendHorizontally: true,
              legendMeasure: (value) {
                if (value == null) return '-';
                return value.toString();
              },

              // legendTitle: (group) => group.groupId,
              startDate: DateTime(2023, 1, 30),
              endDate: DateTime(2023, 2, 6),
              startFromZero: false,
              title: 'Title Chart',
              subtitle: 'subtitle',
              measureLineColor: Colors.purple,
              measureLineThickness: 1,
              measureLabelStyle: const TextStyle(
                color: Colors.green,
                fontSize: 11,
              ),
              domainLineColor: Colors.pink,
              domainLineThickness: 1,
              domainLabelStyle: const TextStyle(
                color: Colors.green,
                fontSize: 14,
              ),
              titleJustify: DJustify.startDrawArea,
              titlePosition: DBehaviorPosition.top,
              innerPadding: 20,
              outerPadding: 0,
              changedListener: (groupId, data) {
                // from package d_method to check on console
                // DMethod.printTitle(
                //   '$groupId : ${data.time.toIso8601String()}',
                //   data.value.toString(),
                // );
              },
              titleStyle: const TextStyle(
                color: Colors.blue,
                fontSize: 16,
                height: 1,
              ),
              subtitleStyle: const TextStyle(
                color: Colors.purple,
                fontSize: 12,
                height: 1,
              ),
              titlePadding: 4,
              groupData: [
                DChartTimeGroup(
                  id: 'Keyboard',
                  color: Colors.blue,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 29),
                    DChartTimeData(time: DateTime(2023, 2, 3, 5), value: 73),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 54),
                  ],
                ),
                DChartTimeGroup(
                  id: 'Monitor',
                  color: Colors.amber,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 15),
                    DChartTimeData(time: DateTime(2023, 2, 1, 5), value: 30),
                    DChartTimeData(time: DateTime(2023, 2, 3), value: 24),
                  ],
                ),
                DChartTimeGroup(
                  id: 'Speaker',
                  color: Colors.green,
                  data: [
                    DChartTimeData(time: DateTime(2023, 2, 1), value: 2),
                    DChartTimeData(time: DateTime(2023, 2, 2, 5), value: 8),
                    DChartTimeData(time: DateTime(2023, 2, 4), value: 30),
                  ],
                ),
              ],
            ),
          ),
        ],
      ),
    );
  }
}

Download details:

Author: indratrisnar.com

Source: https://github.com/indratrisnar/d_chart

#flutter #ui #chart #android #ios #web-development #mobile-apps 

The Development Of an Existing Package Chart for Flutter

Managing Overlay Loading When Fetching Remote Data In Flutter

A simple Flutter package for managing loader when fetching remote data or any long running async task. Flutter overlay loader is easy to use. You can show loader using only write two lines of code.

Overlay loader without overlaying Appbar

drawing drawing

Overlay Loader without overlaying BottomAppBar and also overlaying AppBar

drawing

Getting Started

Installing

dependencies:
  flutter_overlay_loader: ^2.0.0

Import

import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';

How To Use

When start network call then call this line of code..

Loader.show(context,progressIndicator:LinearProgressIndicator());

After finished network call then call :

Loader.hide();

You can customize this loader..

Loader.show(context,
  isSafeAreaOverlay: false,
  isBottomBarOverlay: false,
  overlayFromBottom: 80,
  overlayColor: Colors.black26,
  progressIndicator: CircularProgressIndicator(backgroundColor: Colors.red),
  themeData: Theme.of(context)
    .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.green))
);

You can also check loader is showing or not using the property : Loader.isShown and you can prevent back pressed like this snippet:

WillPopScope(
  child: //TODO , 
  onWillPop:()async => !Loader.isShown
)

Finally dispose call hide method on dispose method :

@override
void dispose() {
  Loader.hide();

  super.dispose();
}

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add flutter_overlay_loader

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  flutter_overlay_loader: ^2.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:flutter_overlay_loader/flutter_overlay_loader.dart';

example/lib/main.dart

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

void main() => runApp(MyApp());

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

class MyHomePage extends StatefulWidget {
  MyHomePage({key,  this.title = "Loader"}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage>
    with SingleTickerProviderStateMixin {
  @override
  void dispose() {
    Loader.hide();
    print("Called dispose");

    super.dispose();
  }

  void _onItemTapped(int index) {}

  @override
  Widget build(BuildContext context) {
    final bottomPadding = MediaQuery.of(context).viewInsets.bottom;

    print("bottomPadding $bottomPadding");
    return WillPopScope(child:  Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
        toolbarHeight: 100,
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          crossAxisAlignment: CrossAxisAlignment.end,
          children: <Widget>[
            Text(
              'Loading...',
            ),
            ElevatedButton(
                child: Text("Show Loader 1"),
                onPressed: () {
                  print("Loader is being shown before ${Loader.isShown}");

                  ///Show default loader here
                  Loader.show(context,
                      progressIndicator: LinearProgressIndicator());

                  print("Loader is being shown after ${Loader.isShown}");

                  ///loader hide after 10 seconds
                  Future.delayed(Duration(seconds: 10), () {
                    Loader.hide();
                    print("Loader is being shown after hide ${Loader.isShown}");
                  });

                }),
            ElevatedButton(
                child: Text("Show Loader 2"),
                onPressed: () {
                  print("Loader is being shown before ${Loader.isShown}");

                  ///Show loader 2 here
                  Loader.show(context,
                      isSafeAreaOverlay: false,
                      isBottomBarOverlay: false,
                      overlayFromBottom: 80,
                      overlayColor: Colors.black26,
                      progressIndicator: CircularProgressIndicator(
                        backgroundColor: Colors.red,
                      ),
                      themeData: Theme.of(context)
                          .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.green))
                  );

                  print("Loader is being shown after ${Loader.isShown}");

                  ///loader hide after 3 seconds
                  Future.delayed(Duration(seconds: 3), () {
                    Loader.hide();

                    print("Loader is being shown after hide ${Loader.isShown}");
                  });

                }),
            ElevatedButton(
                child: Text("Show Loader 3"),
                onPressed: () {
                  ///Show loader 3 here
                  Loader.show(context,
                      isAppbarOverlay: false,
                      overlayFromTop: 100,
                      progressIndicator: CircularProgressIndicator(),
                      themeData: Theme.of(context)
                          .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.black38)),
                      overlayColor: Color(0x99E8EAF6));

                  ///loader hide after 3 seconds
                  Future.delayed(Duration(seconds: 3), () {
                    Loader.hide();
                  });

                }),

            ElevatedButton(
                child: Text("Show Loader 4"),
                onPressed: () {
                  ///Show loader 4 here
                  Loader.show(context,
                      isSafeAreaOverlay: false,
                      progressIndicator: CircularProgressIndicator(),
                      isBottomBarOverlay: false,
                      overlayFromBottom: 80,
                      themeData: Theme.of(context)
                          .copyWith(colorScheme: ColorScheme.fromSwatch().copyWith(secondary: Colors.black38)),
                      overlayColor: Color(0x99E8EAF6)
                  );

                  ///loader hide after 3 seconds
                  Future.delayed(Duration(seconds: 3), () {
                    Loader.hide();
                  });

                }),
          ],
        ),
      ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: 'Home',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.business),
            label: 'Business',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.school),
            label: 'School',
          ),
        ],
        currentIndex: 0,
        selectedItemColor: Colors.amber[800],
        onTap: _onItemTapped,
        iconSize: 50,
      ),
    ), onWillPop:() async => !Loader.isShown);
  }
} 

Download details:

Author: spporan

Source: https://github.com/spporan/FlutterOverlayLoader

#flutter #ui #android #ios #web-development #web 

Managing Overlay Loading When Fetching Remote Data In Flutter

A Flutter Package For Easy Use Of Images That Are Cacheable

Introduction #

Package created for the purpose of uploading images from the internet, giving the possibility of showing a beautiful Shimmer animation while the images are not loading. And it is still possible to create a widget to be shown in case the image upload fails for some reason.

This package is basically a union of two known packages:

Basic Usage

You can use the package on the fly by simple passing a URL of an image to the FancyShimmerImage widget.

FancyShimmerImage(  
  imageUrl: 'https://images.unsplash.com/photo-1465572089651-8fde36c892dd?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80',  
),

That will produce a image that's is cacheable by default and that has a default (grey) Shimmer animation. Similar to result below:

enter image description here

More Advanced Usage

If you don't like the default widget behavior, you can set the background colors of the image, the color of the shimmer base effect, and the color of the highlighted effect.

FancyShimmerImage(  
  imageUrl: 'https://static.businessinsider.sg/2018/12/12/5c1c90f8e04d6243c7019cf6.png',  
  shimmerBaseColor: randomColor(),  
  shimmerHighlightColor: randomColor(),  
  shimmerBackColor: randomColor(),  
)

By randomizing the colors you can have a result similar to this:

enter image description here

Other thing you can do is to configure the direction of the Shimmer and it's speed. In the above example i configured it to have top to bottom direction and 300 milliseconds of speed.

enter image description here

One last step you can configure is to configure the widget that will appear in case the image upload fails for some reason. In this case just pass the desired widget in the errorWidget parameter. If no value is passed, a default error widget will be used.

FancyShimmerImage(  
  imageUrl: 'https://static.businessinsider.sg/2018/12/12/5c1c90f8e04d6243c7019cf6.png',  
  errorWidget: Image.network('https://i0.wp.com/www.dobitaobyte.com.br/wp-content/uploads/2016/02/no_image.png?ssl=1'),
)

enter image description here

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add fancy_shimmer_image

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  fancy_shimmer_image: ^2.0.2

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:fancy_shimmer_image/fancy_shimmer_image.dart';

example/lib/main.dart

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

import 'data.dart';

void main() => runApp(MyApp());

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

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: GridView.builder(
          gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 3,
            mainAxisSpacing: 5,
            crossAxisSpacing: 5,
            childAspectRatio: 1,
          ),
          itemBuilder: (_, i) => FancyShimmerImage(
            imageUrl: dataDefault[i].url,
            shimmerBaseColor: dataDefault[i].shimmerBaseColor,
            shimmerHighlightColor: dataDefault[i].shimmerHighlightColor,
            shimmerBackColor: dataDefault[i].shimmerBackColor,
            errorWidget: dataDefault[i].errorWidget,
          ),
          itemCount: 15,
        ),
      ),
    );
  }
}

Download details:

Author: rodrigobastos.dev

Source: https://github.com/rodrigobastosv/fancy-shimmer-image

#flutter #image #ui #android #ios #web-development 

A Flutter Package For Easy Use Of Images That Are Cacheable

Gradient Borders for inputs and Containers In Flutter

Various borders that use gradient instead of boring plain colors.

Usage

Box borders:

Change your container borders to use fancy gradients:

Container(
  width: 100,
  height: 100,
  decoration: BoxDecoration(
    border: const GradientBoxBorder(
      gradient: LinearGradient(colors: [Colors.blue, Colors.red]),
      width: 4,
    ),
    borderRadius: BorderRadius.circular(16)
  ),
),

Works with both: border radius, and with BoxShape.circle

image

Input borders

You can use GradientOutlineInputBorder as a part of your input decoration:

TextField(
  decoration: InputDecoration(
    border: GradientOutlineInputBorder(
      gradient: LinearGradient(colors: [Colors.red, Colors.blue]),
      width: 2,
    ),
    focusedBorder: GradientOutlineInputBorder(
     gradient: LinearGradient(colors: [Colors.yellow, Colors.green]),
      width: 2
    ),
    label: Text("Example"),
  ),
),

image

Sponsored by

The Code Brothers

Use this package as a library

Depend on it

Run this command:

With Flutter:

 $ flutter pub add gradient_borders

This will add a line like this to your package's pubspec.yaml (and run an implicit flutter pub get):

dependencies:
  gradient_borders: ^1.0.0

Alternatively, your editor might support flutter pub get. Check the docs for your editor to learn more.

Import it

Now in your Dart code, you can use:

import 'package:gradient_borders/gradient_borders.dart';

example/lib/main.dart

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

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

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Gradient borders"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              width: 100,
              height: 100,
              decoration: BoxDecoration(
                  border: const GradientBoxBorder(
                    gradient: LinearGradient(colors: [Colors.blue, Colors.red]),
                    width: 4,
                  ),
                  borderRadius: BorderRadius.circular(16)),
            ),
            const SizedBox(height: 16),
            Container(
              width: 100,
              height: 100,
              decoration: const BoxDecoration(
                border: GradientBoxBorder(
                  gradient:
                      LinearGradient(colors: [Colors.green, Colors.yellow]),
                  width: 4,
                ),
              ),
            ),
            const SizedBox(height: 16),
            Container(
              width: 100,
              height: 100,
              decoration: const BoxDecoration(
                shape: BoxShape.circle,
                border: GradientBoxBorder(
                  gradient:
                      LinearGradient(colors: [Colors.pink, Colors.orange]),
                  width: 4,
                ),
              ),
            ),
            const SizedBox(height: 16),
            const TextField(
              decoration: InputDecoration(
                border: GradientOutlineInputBorder(
                  gradient: LinearGradient(colors: [Colors.red, Colors.blue]),
                  width: 2,
                ),
                focusedBorder: GradientOutlineInputBorder(
                    gradient:
                        LinearGradient(colors: [Colors.yellow, Colors.green]),
                    width: 2),
                label: Text("Example"),
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Download details:

Author: warwas.dev

Source: https://github.com/obiwanzenobi/gradient-borders

#flutter #ui #android #ios #web-development 

Gradient Borders for inputs and Containers In Flutter
Julie Murray

Julie Murray

1629181827

Hire Best Mobile UI designers | Top 10 Mobile App UI Design Companies

In this fast-paced world, businesses need to be present wherever and whenever their clients want them to be. Sales could happen at the break of dawn as well as in the middle of the night. A mobile app is the most agile solution in this respect. It helps you stay within direct reach of your intended customers, within their smartphones; usable with a snap of a finger. 

Looking to launch a new mobile app? Today, the market for mobile app development is huge. And it ranges from large companies to startups. No matter the size of your business, mobile apps can help you connect with customers and provide engaging information that allows them to find out more about your company and the services you provide.

If you need help selecting the mobile app design company that’s right for you, check out this list of the top 10 mobile app design companies.

List Of Top 10 Mobile App UI Design Companies:

  1. Auxano Global Services
  2. The Better Bunch
  3. Seattle Software Developers
  4. AppStudio
  5. PoaTek IT Consulting
  6. Mango Mobile
  7. APPLIFY
  8. Raster
  9. Adrodev
  10. Urban Insight

1.Auxano Global Services

Auxano Global Services is a leading global app designing company, wherein technological solutions are developed to harness and extend human mind potentials innovatively. The structured process helps in creating reliable and empirical UX/UI designs, that add both look and feel value to any digital product. With more than a decade of work experience, their team of senior app designers and cognitive scientists are known to map purposeful product strategies and then develop aesthetic experiences as viable solutions to elevate the user experience to a whole new level.

2. The Better Bunch World

BetterBunch is a team of software developers living for the thrill of a technical challenge. We provide full stack app development for businesses. We have developed 30+ heavy duty projects. We do hourly & project-based work, retainers, agile & waterfall, onsite — whatever your project needs. The core team consists of 16 members, but the network of trusted external talent can be extended to up to 40 professionals. We work best with technology companies that have a CTO but do not have enough in-house resources to cover all development needs.

3. Seattle Software Developers

Seattle Software Developers is a computer software company based out of 4 102nd Ave NE, Bellevue, WA, United States. We’re a colourful assortment of tech nerds, coders, and designers who happen to love what we do. Most of our employees got their start at Microsoft, Google, or Amazon. The experience gained at these tech giants is evident in our work. Our collaborative spirit extends beyond the office: we’re a close-knit bunch that works together, plays together, and even vacations together.

More Results….

#mobile #mobile-apps #mobileuidesigners  #ui #uidesign #uidesigner #topmobileuidesigners  #hiremobileuidesigners #topmobileuidesignersforhire 

Hire Best Mobile UI designers | Top 10 Mobile App UI Design Companies
Mariya James

Mariya James

1629116545

Mobile App Development | Mobile App Trends | UX trends

The State of UI/UX Design in Mobile App Development: Trends for 2021

UI/UX Design plays an important role in Mobile App Development. By using attractive UX design, the developers can build unique mobile applications.

It has been estimated that around 90% of users have stopped using a mobile app because of poor performance. This study has proved that a #high-quality user #experience (UX) design is no longer a competitive edge alone. Instead, UX is a critical element in ensuring long-term market #success.

Read Here: https://bit.ly/3zlFaRu
.
.
.
.
.
#ui #ux #userexperience #uxdesign #mobileappdevelopment #mobileapplications #design #success #BestUserFriendlyUXUI #latesttrends #LatestUITechnology #TopUXDesigns #TrendsInUXDesignFor2021, #uxdesigner #trends2021 #topmobileapplicationdevelopmentcompanies #Bestmobileapplicationdevelopers #webdesign #outsourcemobileappdevelopmentindia #Hireremotemobileappdevelopers

Mobile App Development | Mobile App Trends | UX trends
Dee  Jacobi

Dee Jacobi

1628658000

How to Application UI Design with Corona virus (COVID-19)

The following video is an intro and dashboard view of the coronavirus application (COVID-19) build with Flutter adding illustrations so that the display looks better. 
#ui 

How to Application UI Design with Corona virus (COVID-19)