Git Product home page Git Product logo

jeffdev2018 / all-about-flutter Goto Github PK

View Code? Open in Web Editor NEW

This project forked from singh1aryan/intro-to-flutter

0.0 1.0 0.0 2.23 MB

🎸 Flutter - Mobile Application Development || Firebase functions || Database || Push notifications || Machine Learning Kit || Android || Flutter || React-Native || Flutter-learning-application || UI, Widgets, Layouts || Open Source || Social Media || Tech News || Flutter Snippets || Dynamic Surveys

Java 0.66% Objective-C 1.38% Dart 96.40% TypeScript 1.56%

all-about-flutter's Introduction

All About Flutter

  • Make amazing Mobile Apps

Introduction

  • What's Flutter - Cross native platform to build Mobile applications
  • Easy to get started, perfect for hackathons, super fast to code!

Things you need to know before coming here -

  • print() function in any programming language

Getting started

Open source Flutter Apps

Awesome GitHub people

Other resources

  • The best way to get started is to work with real life applications with some source code in hand
  • You download a starter code and then build from there. Start with an easy project, move your way up and change things as you go
  • Covers everything from Basic layouts to Google maps or advanced UI

Everything is a Widget

Multi-child layout widgets

  • Text
  • Row - children - Expanded
  • Column
  • Center
  • Container - child, decoration
  • Stack
  • Tab View, Grid View
  • Expanded
  • Icon Button
  • Raised Button
  • Image.asset
  • List View, List Tile
  • Table
  • Wrap

Single-child layout widgets

  • Slivers
  • SliverList
  • SliverGrid
  • SliverAppBar
  • DeMystified

Styling

  • Padding
  • Align
  • Aspect Ratio
  • Baseline -
  • Center
  • Constraint Box
  • Container
  • Fitted Box
  • Intrinsic Height, Weight
  • Offstage
  • Transform

Important Diagrams

Screen Shot 2019-10-06 at 10 22 10 PM

Screen Shot 2019-10-06 at 10 41 15 PM

Screen Shot 2019-10-06 at 10 41 25 PM

Async/Await with Flutter

fetch() async {

    var url = "API-HERE";
    var res = await http.get(url);
    var body = jsonDecode(res.body);

    // body is your API body 
}

BloC pattern Flutter

  • Coming soon

Machine Learning with Flutter

  • Using the ML Kit with Flutter

Firebase + Flutter

  • Firebase auth - login with google or Oauth
  • Firebase Firestore - Realtime database
  • Firebase push notifications - Notify the user when a new recipe is added
  • Firebase analytics - how the app in performing
  • Firebase ML kit - built in ml models for text, face recognition

Accessibility Coding - Flutter vs Android

  • Exclude Semantics
  • Merge Semantics
  • Voice Overs
  • Color Combination
  • It's much more defined in Android, but definitely coming up in Flutter
  • For example: We can add things like content description to a button, textView etc in Android for voice overs

Problems - Flutter issues

Android vs Flutter - Firebase

  • Firebase is definitely easier to implement for Flutter, you can do it in 20 lines of code depending on the list view you make
  • Android has crazy recycler views which make everything so hard, and integrating firebase + recycler view has about 200 articles, and you just cannot master it
  • Pushing data is also easier in Firebase, there's literally an onTap() method which allows you to send a snapshot of the data

Navigation - Flutter

  • Navigation is really easy, and if you know OOPS, then you'll master it in seconds
  • You just need to pass in the object and that's it. Pass it everywhere (literally!) - for the basics
  • Any data is passed in an Object which can be parsed in the next class

Firebase Functions - Notifications

  • Implemented fully optimized firebase functions and push notifications
  • The user is notified in real time when a new item is added to the recipes_list
  • Used Node JS and TypeScript to create a firebase function which does this

Tab Views - Android vs Flutter

  • Again, everything including this is very straightforward in Flutter
  • Make a Tab View, fill in the required parameters and you're all set
  • Tab Controller, TabBar for the Labels and TabBarView for the actual stuff in each tab
  • You could add literally any widget in there - Text, ListView etc
  • It's a bit more complex and well defined in Android
  • We need view pagers, adapters, and fragments to add a tab view
  • We can have different UIs for the fragments, but it's more time consuming to understand and implement

UI - Flutter vs React-Native vs Android

  • Android works with XML layouts, so that's in a separate file and much more readable in a sense
  • Flutter and RN have a one file system, where you define the rules and UI
  • Flutter uses Widgets for literally everything, from TextViews to TabViews - they're called 'Widgets'.
  • RN has components and we have to import them from 'react-native' to use them
  • Styling: Android - Using XML, Flutter - inside widgets - so if you want padding => you wrap the widget in Padding() widget with some padding, RN: you define const style: Stylesheet and add your styles there - similar to the web style where you have css
  • Animations: Android and RN is complicated for Animations, Flutter is very straightforward
  • Clean UI: All three can be used, but for static or single/simple pages - Android works out the fastest
  • What's the best? I would say all 3, so start learning ASAP

Computer vision ML integration

  • We can integrate a machine learning model to predict the food/recipe posted
  • We can probably look at a dataset of recipes and predict if it's going on the right path
  • Merging the ML code soon!

Different Code snippets -> Beginner - Intermediate - Advanced

Basic class layout

class App extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      home: Home(),
      theme: ThemeData(primaryColor: PrimaryColor),//add-your-color here || or remove this
      debugShowCheckedModeBanner: false,
    );
  }
}

class Home extends StatefulWidget{
  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return new _HomeState();
  }
}

class _HomeState extends State<Home>{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Column()
    );
}

Simple widgets -> widgets folder in lib

Using conditionals with Flutter

child: users.length <= 0
            ? Center(
                child: EmptyState(
                  title: 'Oops',
                  message: 'Add form by tapping add button below',
                ),
              )
            : ListView.builder(
                addAutomaticKeepAlives: true,
                itemCount: users.length,
                itemBuilder: (_, i) => users[i],
              ),
      )

APIs - Flutter

Simple API fetch function

fetch() async {

    var url = "API-HERE";
    var res = await http.get(url);
    var body = jsonDecode(res.body);

    // body is your API body 
}

Parsing API - Eg: staggered tile

for(int i=0;i<body[0]['staggered_tiles'].length;i++){
    _staggeredTiles.add(new StaggeredTile.count(
      body[0]['staggered_tiles'][i]['cross_axis'],// body is what we get from the API
      body[0]['staggered_tiles'][i]['main_axis']// body is what we get from the API
    ));
}     

Parsing 2 APIs in one - Eg: pager view

if (body[i][0]['type'] == 'donut') {
        List<LabelPieSales> _d = [];
        for (int j = 0; j < body[i][0]['data'].length; j++) {
          _d.add(new LabelPieSales(
              body[i][0]['data'][j]['year'], body[i][0]['data'][j]['sales']));// body is what we get from the API
        }
        _wid_top.add(new Container(
          height: 200,
          width: 200,
          child: DonutChartWidget.withSampleData(_d),
        ));
      }
      else if (body[i][0]['type'] == 'label-pie') {
        List<LabelPieSales> _d = [];
        for (int j = 0; j < body[i][0]['data'].length; j++) {
          _d.add(new LabelPieSales(
              body[i][0]['data'][j]['year'], body[i][0]['data'][j]['sales']));// body is what we get from the API
        }
        _wid_top.add(new Container(
          height: 200,
          width: 200,
          child: SimpleBarChart.withSampleData(_d),
        ));
      }

API with Notifier - Eg: real time interaction with buttons and API

return Container(
      padding: const EdgeInsets.all(4.0),
      child: appState.isFetching
          ? CircularProgressIndicator()
          : appState.getResponseJson() != null
          ? ListView.builder(
              primary: false,
              shrinkWrap: true,
              itemCount: appState.getResponseJson().length,
              itemBuilder: (context, index) {
                return Container(
                  height: 100,
                  width: 100,
                  child: graph(appState.getResponseJson()),
                );
              },
            )
          : Text("Press Button above to fetch data"),
    );

SQL database + Flutter

Initializing SQL database

initDB() async {
  return await openDatabase(
    join(await getDatabasesPath(), 'graphs_database.db'),
    onCreate: (db, version) {
      return db.execute(
        "CREATE TABLE graphs(id INTEGER PRIMARY KEY, type TEXT)",
      );
    },
    version: 1,
  );
}

State management - Eg: adding new objects in SQL database

floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () async {
          Dog dog = new Dog(id: _id, name: "name",age: 22);
          await insertDog(dog);
          setState(() {
            _id += 1;
          });
        },
      ),

Comparing SQL and API stuff - making a local push notification

List<Graph> graphs_sql = await graphs();
            List<String> graphs_sql_types = [];
            for(int i=0;i<graphs_sql.length;i++){
              graphs_sql_types.add(graphs_sql[i].type);
            }
            if (graphs_sql.length != _types.length) {
              for (int i = 0; i < _types.length; i++) {
                if(!graphs_sql_types.contains(_types[i])){ // add only if a new type
                  await insertGraph(new Graph(id: i, type: _types[i]));
                }
              }
            }

Web views for Flutter - Eg: Displaying websites inside your app

launchUrl() {
    setState(() {
      urlString = controller.text;
      flutterWebviewPlugin.reloadUrl(urlString);
    });
  }

Class Layouts

class News{
  String dateAdded;
  String title;
  String body;
  String level;
  String category;

  News(this.dateAdded, this.title, this.body, this.level, this.category);

}

class Record {
  final String name;
  final int votes;
  final DocumentReference reference;

  Record.fromMap(Map<String, dynamic> map, {this.reference})
      : assert(map['name'] != null),
        assert(map['votes'] != null),
        name = map['name'],
        votes = map['votes'];

  Record.fromSnapshot(DocumentSnapshot snapshot)
      : this.fromMap(snapshot.data, reference: snapshot.reference);

  @override
  String toString() => "Record<$name:$votes>";
}

Height and Width of screen

double _height = MediaQuery.of(context).size.height;
double _width = MediaQuery.of(context).size.width;

init state - initialize any lists/images for the screen

@override
  void initState() {
    // TODO: implement initState
    super.initState();
    _image = {url};
    localList1 = globalList1;
    localList1 = globalList2;
    }

Firebase stuff:

Firebase Function- Eg: push notifications

export const sendToTopic = functions.firestore
    .document('recipes/{recipyId}')
    .onCreate(async snapshot => {
        // const recipe = snapshot.data();
        const payload : admin.messaging.MessagingPayload = {
            notification: {
                title: 'new recipe added, check it out',
                body: 'Make it and eat it'
            }
        };

        return fcm.sendToTopic('recipes', payload);
    });

Firebase Firestore

@override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Recipes for you')),
      body: _buildBody(context),
    );
  }

  Widget _buildBody(BuildContext context) {
    return StreamBuilder<QuerySnapshot>(
      stream: Firestore.instance.collection('recipes').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) return LinearProgressIndicator();
        return _buildList(context, snapshot.data.documents);
      },
    );
  }

Intgerating Asymmetric view with Firestore

  • Google Codelabs gave me the Asymmetric view, and I wanted to combine it with Firestore
  • It's definitely tricky as you can show data directly from the Firestore to a Listview, but it's a little tricky to store it and send the whole list to another class
  • Try it first, and then come back to this code!
  • List<Recipe> recipe_list = [];
    //    snapshot.map((data) => recipeList(context, data).toList());
    for(int i=0;i<snapshot.length;i++){
      Recipe recipe = Recipe.fromSnapshot(snapshot[i]);
      recipe_list.add(recipe);
    }
    return AsymmetricView(products: recipe_list,);
    

Apps

Practice by making these Apps

  • API: News, Movies, Restaurants
  • Social Media: Blogs, Recipes
  • Games: Tic-Tac-Toe, Minesweeper, Guessing Cards, 2048, 15
  • Animations: Tinder cards, Sliding, Modals, Rainfall, Pizza maker, Payment System
  • Simple: Todo, Navigation, Login, Drawers
  • UI: Dashboard, Payment system, Shopping, Recipe design
  • Machine learning: Text to Speech, Computer vision, Chatbots

Hackathons

Why to use Flutter?

  • Quick API integration - fetching, parsing, using
  • Using Networking, web sockets, chatting features
  • Using Open Source material design for interactive UI
  • Take advantage of Open source projects - for UI
  • Firebase quick integration - notification, login, database
  • Machine learning kit powered by Firebase - MLKit
  • Computer vision library by MLKit

Hackathon Projects made using Flutter

  • Devpost links

Important!

  • Feel free to make a pull request if you find something wrong/ can be improved
  • Don't forget to star or fork the repo, I add things every once a while

all-about-flutter's People

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.