Skip to content

Instantly share code, notes, and snippets.

@sab99r
Last active June 4, 2022 10:08
Show Gist options
  • Save sab99r/3f46f4868ad9928ac631822db21a6fdf to your computer and use it in GitHub Desktop.
Save sab99r/3f46f4868ad9928ac631822db21a6fdf to your computer and use it in GitHub Desktop.
Flutter Quick Notes #Flutter

Flutter Cheet Sheet

1. Close Top Stack Widget (Eg. Bottom Sheet, Dialog, etc.)

Navigator.of(context).pop();

//In StatefulWidget => State Class context is like widget flutter defined object we can use it without defining

2. Theme

//set theme of app
MaterialApp(
    theme: ThemeData(
        primarySwatch : Colors.blue,
        accentColor : Colors.yellow,
    ),
);

//To access theme data
Theme.of(context).primaryColor;

//Copy current theme data and overide with new style
MaterialApp(
    theme : ThemeData(
        appBarTheme : AppBarTheme(
            textTheme: ThemeData.light().textTheme.copyWith(
                title:TextStyle(
                    fontFamily : 'OpenSans',
                    fontSize : 20
                )
            )
        )
    ),
);

3. Add Assets

#Add Images
  assets:
   - assets/images/waiting.png
#To Access the Image -> Image.asset("assets/images/waiting.png")


# Add Fonts
  fonts:
    - family: OpenSans
      fonts:
        - asset: assets/fonts/OpenSans-Regular.ttf
        - asset: assets/fonts/OpenSans-Bold.ttf
          weight: 700
    - family: Quicksand
      fonts:
        - asset: assets/fonts/Quicksand-Regular.ttf
        - asset: assets/fonts/Quicksand-Bold.ttf
          weight: 700

#defines weight after Bold font to Enable that particular font When use the Bold property in TextStyle

4. Flexible

//Uses All the available space
Flexible(
    flex : 2, //Like CSS flex
    fit : FlexFit.tight
)

//Alternatively use Expandable 
Expandable(
    flex : 2
)

5. Routes

//push
Navigator.of(context).push(
    MaterialPageRoute(
        builder:(_){
            return Page2Screen();
        }
    );
)

//pushNamed

//1. Define routes in -> MaterialApp  main.dart
MaterialApp(
    routes:{
        '/': (_) => HomePage(), // '/' is initialRoute so no need to mention home seperately if add this
        '/about' : (_) =>  AboutPage(),
        '/product-details' : (_) =>  ProductDetailsPage(),
    }
)

//2. Call named route
onTap:(){
    Navigator.of(context).pushNamed(
        '/product-details',
        arguments:{
            'id':id,
            title:title
        }
    )
}

//3. Receive Arguments in ProductDetailsPage build method
Widget build(BuildContext context) {
    final routeArgs = ModelRoute.of(context).settings.arguments as Map<String,String>;
    final id = routeArgs['id'];
    final title = routeArgs['title'];
}

Media Query (Responsive Design)

var width = MediaQuery.of(context).size.width;
var height = MediaQuery.of(context).size.height;

//Height 60% 
var heightInPercentage = MediaQuery.of(context).size.height * 0.6;

//Get Widget Size (Store it in variable) 
var appBarHeight = appBar.preferredSize.height;

//To Get Accurate Percentage Size remove appBar and Status Bar Height if included
var heightIn60Percentage = (MediaQuery.of(context).size.height - appBar.preferredSize.height - MediaQuery.of(context).padding.top) * 0.6;

SystemChrome

Portrait Mode Only

//In main function
SystemChrome.setPreferredOrientations([
    DeviceOrientation.portraitUp,
    DeviceOrientation.portraitDown
]);

Build Based On Parent Size

LayoutBuilder(
    builder : (context,constraints){
        return Container(
            height : constraints.maxHeight * 0.6,//60% Height Of Parent
        );
    }
)

Check Orientation

//Check Landscape
if(MediaQuery.of(context).orientation == Orientation.landscape){

}

Check Platform

import 'dart:io';

if(Platform.isIOS){

}

Performance Tips

Add const on possible Static (Immutable) Widgets
Container(
    child: const Text("Hello World"),
);

Fix ListView State Bugs (Add key to the root list item element)

Container(
    key : UniqueKey()
);
//Or (Best)
Container(
    key : ValueKey(item.id)
);

// In Custome Widget Constructore key should be passed to super
MyCustomWidget({Key key,this.title}) : super(key : key);

Fix Build Issues

1. Navidate to android directory

./gradlew clean
./gradlew build
./gradlew dependencies

2. Check .packages for any dependend un supported packages installed

3. Run flutter packages get --verbose to find issues in package.yml libraries

4. flutter run -v to detect any unknown error

Fix Firebase POD Install Fail in M1 Mac

cd ios/
arch -x86_64 rm -rf Podfile.lock
arch -x86_64 pod install --repo-update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment