flutter code snippets

Flutter - Check if Index exist in a List
List<int> numbers = [1, 2, 3, 4, 5];

//Check if index 6 exists
if (numbers.asMap().containsKey(7)) {
  print('Index exists');
} else {
  print('Index does not exist');
}
How to convert String to Int in Flutter
String a = "3"

print(int.parse(a));
Flutter - Trim a String
String myString = "  Hello, World!  ";
String trimmedString = myString.trim();
print(trimmedString); // Output: "Hello, World!"
Flutter - ScrollController not attached to any scroll views
if (_scrollController.hasClients) {
    _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        curve: Curves.easeOut,
        duration: const Duration(milliseconds: 300),
    );
}
TextField Widget Padding in Flutter
TextField(
    decoration: InputDecoration(
        contentPadding: EdgeInsets.symmetric(
            horizontal: 15.0, 
            vertical: 20.0
        ),
        hintText: 'Write your message...',
    ),
),
Remove Back Button from Flutter Appbar
AppBar(
  automaticallyImplyLeading: false, // Remove the back button
  title: Text('My App'),
),
Create Alert Dialog in Flutter
_showAlertDialogue() {
  showDialog(
    context: context,
    builder: (BuildContext context) {
      return AlertDialog(
          actionsAlignment: MainAxisAlignment.center,
          alignment: Alignment.topRight,
          // buttonPadding: EdgeInsets.all(0),
          title: const Text(
            'Alert Header',
            style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16.0),
          ),
          content: SingleChildScrollView(
            child: Text('Text description of some topic.')
          ),
          actions: <Widget>[
            TextButton(
                child: const Text('Cancel'),
                onPressed: () {
                  Navigator.of(context).pop();
                },
            ),
          ],
      );
    },
  );
}
Error - Android Gradle plugin requires Java 11 to run. You are currently using Java 1.8.
// Run below commands to update JDK version on your mac

brew tap homebrew/cask-versions

brew install --cask zulu11
Flutter run app in release mode
flutter run --release
Flutter Container Widget
Container(
  padding: EdgeInsets.all(10.0),
  margin: EdgeInsets.all(10.0),
  color: Colors.white,
  child: Text('Hello World'),
)
Set height and width of Button in Flutter
SizedBox(
  width: 250,
  height: 50,
  child: OutlinedButton(
    onPressed: () {
      print("hello world");
    },
    child: const Text("English", style: ThemeText.btnA),
  ),
),
Create rounded border button in Flutter
OutlinedButton(
  onPressed: null,
  style: ButtonStyle(
    shape: MaterialStateProperty.all(
      RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(30.0),
      ),
    ),
  ),
  child: const Text("Share"),
),
Ternary Conditional operator in Flutter(Dart)
String message = isLoggedIn ? 'Hello again' : 'Please sign up';
Set width and height of a button in Flutter
ElevatedButtonTheme(
  minWidth: 200.0,
  height: 100.0,
  child: ElevatedButton(
    onPressed: () {},
    child: Text("test"),
  ),
);
Round Container with Image in Flutter
Container(
  width: 200.0,
  height: 200.0,
  margin: const EdgeInsets.all(50.0),
  decoration: const BoxDecoration(
    borderRadius: BorderRadius.all(
        Radius.circular(100.0),
    ),
    image: DecorationImage(
      image: NetworkImage('https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
      fit: BoxFit.cover,
    ),
  ),
),
Define Int type value in class Flutter
class User {
  int? id;
  String? name;

  Picture({
    this.type,
    this.name
  });

  User.fromJson(Map<dynamic, dynamic> json)
      : id = json['id'],
        name = json['name'];
}
Pass Data to Stateless Widget in Flutter
class FirstScreen extends StatelessWidget {
  const FirstScreen({Key? key}) : super(key: key);
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("First Screen"),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: ElevatedButton(
          onPressed: () {
            Navigator.push(
              context,
              MaterialPageRoute(
                builder: (context) => const SecondScreen(
                  title: 'Second Screen',
                  description: 'Second Screen Description',
                ),
              ),
            );
          },
          child: const Text('Go to Second Screen'),
        ),
      ),
    );
  }
}

class SecondScreen extends StatelessWidget {
  const SecondScreen({Key? key, required this.title, required this.description}) : super(key: key);

  final String title;
  final String description;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(title),
      ),
      body: Padding(
        padding: const EdgeInsets.all(16.0),
        child: Text(description),
      ),
    );
  }
}
How to remove debug banner in Flutter app
MaterialApp(
    title: 'My App',
    debugShowCheckedModeBanner: false,
    theme: ThemeData(
        primarySwatch: Colors.blue,
    ),
    home: const HomePage(),
);
Prevent device rotation in Flutter
import 'package:flutter/services.dart'

class MyApp extends StatelessWidget {
    @override
    Widget build(BuildContext context) {
      SystemChrome.setPreferredOrientations([
        DeviceOrientation.portraitUp,
        DeviceOrientation.portraitDown,
      ]);
      return new MaterialApp();
    }
  }
Flutter project default
import 'package:flutter/material.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(
        // 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: const MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key, required 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
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            const Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: const Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}
Dismiss the mobile screen keyboard in Flutter
ElevatedButton(
    onPressed: () {
        // This code will hide the mobile keyboard screen
        FocusManager.instance.primaryFocus?.unfocus();
    },
    child: const Text('Hide Keyboard'),
)
Flutter secure storage
import 'package:flutter_secure_storage/flutter_secure_storage.dart';

class SecureStorage {
  // Create an instance and enable secure encryption:
  static const storage = FlutterSecureStorage(
      aOptions: AndroidOptions(encryptedSharedPreferences: true));

  static Future<void> saveData(String key, String value) async {
    await storage.write(key: key, value: value);
  }

  static Future<String?> readData(String key) async {
    return await storage.read(key: key);
  }

  static Future<Map<String, String>> readAllData(String key) async {
    return await storage.readAll();
  }

  static Future<bool> containsData(String key) async {
    return await storage.containsKey(key: key);
  }

  static Future<void> deleteData(String key) async {
    await storage.delete(key: key);
  }

  static Future<void> deleteAllData() async {
    await storage.deleteAll();
  }
}
Text with Styles
Text(
  "Text With Styles",
  style: TextStyle(
    color: Colors.grey[800],
    fontWeight: FontWeight.bold,
    fontSize: 18.0,
  ),
)
Send Form Data in HTTP POST request in Flutter
import 'package:http/http.dart' as http;

void main() {
    // This will be sent as form data in the post requst
    var map = new Map<String, dynamic>();
    map['username'] = 'username';
    map['password'] = 'password';

    final response = await http.post(
        Uri.parse('http/url/of/your/api'),
        body: map,
    );

    print(response.body);
}
Send HTTP POST request in Flutter or Dart
import 'dart:convert';
import 'package:http/http.dart' as http;

void main() async {
    http.Response response = await createUser("Bob", "engineer");
    
    print(response.body);
}

Future<http.Response> createUser(String name, String job) {
    return http.post(
        Uri.parse('https://reqres.in/api/users'),
        headers: <String, String>{
            'Content-Type': 'application/json; charset=UTF-8',
        },
        body: jsonEncode(<String, String>{
            'name': name,
            'job': job
        }),
    );
}
Send HTTP Get request in Flutter or Dart
import 'dart:convert';
import 'package:http/http.dart' as http;

void main {
    final response = await http.get(Uri.parse("https://domain.com/endpoint?data=hello"));

    String responseData = utf8.decode(response.bodyBytes);

    print(json.decode(responseData));
}
Send a Map in query parameter of http request in Flutter
import 'dart:convert';

// map data
var myMap = {
    'id': [1, 2, 3],
    'names': ['John', 'Rick', 'Carl']
}

// create url with map data in query string
Uri url = Uri.http(
    'domain.com',
    '/endpoint',
    {
      'mapData': jsonEncode(myMap),
    },
);
  
// Print the url
print(url);
Find number of days between two dates in Flutter or Dart
DateTime dateA = DateTime.parse('2021-08-19'); 
DateTime dateB = DateTime.parse('2021-09-27');

final numOfDays = dateB.difference(dateA).inDays;

print('$numOfDays');
Get current timestamp in flutter or dart
var timestamp = DateTime.now().millisecondsSinceEpoch.toString()
print(timestamp);
Avoid setState after dispose solution
@override
void setState(VoidCallback fn) {
    if(mounted) {
        super.setState(fn);
    }
}
Load on scroll
final _scrollController = ScrollController();

@override
  void initState() {
  super.initState();
  _scrollController.addListener(_onScroll);
}

void _onScroll() {
  // call load/fetch method when it reaches the bottom of a list 
  if (_isBottom) context.read<PostBloc>().add(PostFetched());
}

bool get _isBottom {
  if (!_scrollController.hasClients) return false;
  final maxScroll = _scrollController.position.maxScrollExtent;
  final currentScroll = _scrollController.offset;
  return currentScroll >= (maxScroll * 0.9);
}

//don't forget to dispose it
@override
void dispose() {
  _scrollController
  ..removeListener(_onScroll)
  ..dispose();
  super.dispose();
}
Center the title in appbar flutter
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("APP DEMO"),
        centerTitle: true //This will center the text
      ),
      body: Container()
    );
  }
}
Full width Container in Flutter
Container(
    color: const Color(0xffCCCCCC),
    width: double.infinity, // Code to assign full width
    child: const Text('Hello World'),
)
Assign width in percentage to flutter container
class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    double width50 = MediaQuery.of(context).size.width * 0.50;
    
    return Container(
        width: width50,
        child: const Text('Some Text'),
      );
  }
}
String to double conversion in flutter [Dart]
String val = "1.8";
double result = double.parse(val);
print(result);
// -> 1.8
Create 10 container widgets using loop flutter
Column(
    children: [
        for (int i = 0; i < 9; i++) Container(child: Text(i))
    ],
)
Elevated Button
ElevatedButton(
  style: ElevatedButton.styleFrom(
    primary: Colors.blue, //button's fill color
    onPrimary: Colors.red, //specify the color of the button's text and icons as well as the overlay colors used to indicate the hover, focus, and pressed states
    onSurface: Colors.orange, //specify the button's disabled text, icon, and fill color
    shadowColor: Colors.black, //specify the button's elevation color
    elevation: 4.0, //buttons Material shadow
    textStyle: TextStyle(fontFamily: 'roboto'), //specify the button's text TextStyle
    padding: const EdgeInsets.only(top: 4.0, bottom: 4.0, right: 8.0, left: 8.0), //specify the button's Padding
    minimumSize: Size(20, 40), //specify the button's first: width and second: height
    side: BorderSide(color: Colors.yellow, width: 2.0, style: BorderStyle.solid), //set border for the button
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(35.0)), // set the buttons shape. Make its birders rounded etc
    enabledMouseCursor: MouseCursor.defer, //used to construct ButtonStyle.mouseCursor
    disabledMouseCursor: MouseCursor.uncontrolled, //used to construct ButtonStyle.mouseCursor
    visualDensity: VisualDensity(horizontal: 0.0, vertical: 0.0), //set the button's visual density
    tapTargetSize: MaterialTapTargetSize.padded, // set the MaterialTapTarget size. can set to: values, padded and shrinkWrap properties
    animationDuration: Duration(milliseconds: 100), //the buttons animations duration
    enableFeedback: true, //to set the feedback to true or false
    alignment: Alignment.bottomCenter, //set the button's child Alignment
  ),
    onPressed: () => {} , //set both onPressed and onLongPressed to null to see the disabled properties
    onLongPress: () => {}, //set both onPressed and onLongPressed to null to see the disabled properties
    child: Text('ElevatedButton')
),
Convert to two digits
int_name.toString().padLeft(2, '0');
string_name.padLeft(2, '0');
GetX with flutter
import 'package:get/get.dart';
import 'package:path to datastoring file/dataFileName.dart';//path to data file

class className {
	final dataFileClassName = Get.find<dataFileClassName>();

	//Set Data
	dataFileClassName.boolVarName.value = true;
	dataFileClassName.stringVarName.value = "Some Text";
	dataFileClassName.floatVarName.value = 2.0;
	dataFileClassName.intergerVarName.value = 10;
	dataFileClassName.arrayVarName.value = ["1", "2", "3"];

	//Read Data
	dataFileClassName.boolVarName.value;
	dataFileClassName.stringVarName.value;
	dataFileClassName.floatVarName.value;
	dataFileClassName.intergerVarName.value;
	dataFileClassName.arrayVarName.value;
}


// User data file
import 'package:get/get.dart';

class dataFileClassName extends GetxController {
  RxBool boolVarName = false.obs;
  RxString stringVarName = "Loading".obs;
  RxDouble floatVarName = 0.0.obs;
  RxInt intergerVarName = 0.obs;
  RxList arrayVarName = [].obs;
}
Call back function from one class to another
class Class1Name{
    Class2Name(functionName: functionName);

    void functionName(){
        //desired actions
    }
}

class Class2Name {
    final VoidCallback functionName;
    Class2Name({@required this.functionName});

    //call function
    functionName();
}

https://www.digitalocean.com/community/tutorials/flutter-widget-communication
Convert a double to an int in Dart or Flutter
double _data = 2.0;
_data = _data.toInt();
Add some delay before executing the code in Flutter
Future.delayed(const Duration(milliseconds: 500), () {
    // DO SOMETHING HERE
});
Add launcher or mobile app icon in Fluter
// add package - flutter_launcher_icons
// package_link - https://pub.dev/packages/flutter_launcher_icons
// Add package in dev dependencies

// pubspec.yaml file
dev_dependencies:
  flutter_launcher_icons: "latest_version"

flutter_icons:
  android: true
  ios: true
  image_path: "assets/icons/icon.png"

//Now run below commands to generate icons
flutter pub get
flutter pub run flutter_launcher_icons:main
Change mobile app name in Flutter
//For Android open - android/app/src/main/AndroidManifest.xml
// change - my_app_name with your app name
<application
        android:name="io.flutter.app.FlutterApplication"
        android:label="my_app_name"
        android:icon="@mipmap/ic_launcher">

//For IOS open - ios/Runner/Info.plist
<key>CFBundleName</key>
<string>my_app_name</string>
Change click action of left AppBar icon in Flutter
AppBar(
    title: Text("App Header"),
    leading: GestureDetector(
        onTap: () { print("Hello click"); },
        child: Icon(
            Icons.menu, //Change icon here
        ),
    ),
)
Convert text of Text widget to uppercase or lowercase in Flutter
//Convert to uppercase
Text(
    "Hello World".toUpperCase(),
),

//Convert to lowercase
Text(
    "Hello World".toLowerCase(),
),
Add spacing between characters of Text widget Flutter
Text(
    "Lotis Mobile app",
    style: TextStyle(
        letterSpacing: 3.0, //This will all spacing between letters
    ),
)
Center Row widget children vertically and horizontally Flutter
Row(
    crossAxisAlignment: CrossAxisAlignment.center,
    mainAxisAlignment: MainAxisAlignment.center,
    children: [
        Text("text 1"),
        Text("text 2"),
    ]
)
Add loader in Flutter mobile app
Center(
    child: CircularProgressIndicator(
        backgroundColor: Color(Colors.blue),
        valueColor: AlwaysStoppedAnimation(Colors.white),
        strokeWidth: 4,
    ),
)
Change circular progress indicator color in Flutter
CircularProgressIndicator(
    backgroundColor: Color(Colors.white),
    valueColor: AlwaysStoppedAnimation(Colors.red),
    strokeWidth: 3,
),
Add background image to container in Flutter
Container(
    decoration: BoxDecoration(
        image: DecorationImage(
            image: NetworkImage('https://placeimg.com/500/500/any'),
            fit: BoxFit.cover,
        ),
    ),
)
Text Button
TextButton(  
    child: Text('Button Text', style: TextStyle(fontSize: 20.0),),  
    onPressed: () {},  
),

https://www.kindacode.com/article/working-with-textbutton-in-flutter/
Simple Gradient in Container
Container(
              decoration: BoxDecoration(
                gradient: LinearGradient(
                  begin: Alignment.topCenter,
                  end: Alignment.bottomCenter,
                  colors: [
                    Colors.indigoAccent[700],
                    Colors.white,
                  ],
                ),
              )),
MediaQuery.of(context)
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
box shadow
new Container(
    height: 200.0,
    decoration: new BoxDecoration(
        boxShadow: [
          color: Colors.white, //background color of box
          BoxShadow(
            color: Colors.red,
            blurRadius: 25.0, // soften the shadow
            spreadRadius: 5.0, //extend the shadow
            offset: Offset(
              15.0, // Move to right 10  horizontally
              15.0, // Move to bottom 10 Vertically
            ),
          )
        ],
    ),
    child: new Text("Hello world"),
);
Rounded outline button Flutter
OutlineButton(
    onPressed: () {},
    child: Text('Sign in'),
    shape: new RoundedRectangleBorder(
        borderRadius: new BorderRadius.circular(30.0),
    ),
),
Remove focus from TextField on button click in Flutter
onTap: () {
    WidgetsBinding.instance.focusManager.primaryFocus?.unfocus();
}
Use ListView.builder with other widgets in scroll area Flutter
SingleChildScrollView(
    physics: ScrollPhysics(),
    child: Column(
        children: <Widget>[
            Container(
                color: Color(0xffFFFFFF),
                child: Text('Hello Wold')
            ),
            ListView.builder(
                physics: NeverScrollableScrollPhysics(),
                itemCount:18,
                itemBuilder: (context,index){
                    return  Text('Some text');
            })
        ],
    ),
),
Navigate to a page in Flutter
Navigator.push(
    context,
    MaterialPageRoute(
        builder: (context) => PageName(
          data: data,
        ),
    ),
);
Add image with circular shape from corners in Flutter
Container(
    height: 200.0,
    child: ClipRRect(
        borderRadius: BorderRadius.circular(15.0),
        child: Image.network(
            "https://placeimg.com/640/480/any",
            fit: BoxFit.cover,
        ),
    ),
),
Decoration BoxDecoration Container
BoxDecoration myBoxDecoration() {
  return BoxDecoration(
    border: Border.all(
      width: 1, 
    ),
  );
}
BoxDecoration myBoxDecoration() {
   return BoxDecoration(
     border: Border(
       left: BorderSide(
         width: 2.0,
         color: Colors.green,
       ),
       right: BorderSide(
         width: 2.0,
         color: Colors.green,
       ),
       top: BorderSide(
         width: 2.0,
         color: Colors.green,
       ),
       bottom: BorderSide(
         width: 2.0,
         color: Colors.green,
       ),
     ),
     borderRadius: BorderRadius.all(
       Radius.circular(10.0),
     ),
   );
 }
Change the color of icons in appbar flutter
Scaffold(
  appBar: AppBar(
    iconTheme: IconThemeData(
      color: Color(0xffFF0000), //OR Colors.red or whatever you want
    ),
    title: Text("Title"),
    backgroundColor: Color(0xffFAFAFA),
  ),
)
Add a single widget as a sliver in Flutter
Scaffold(
  body: CustomScrollView(
    slivers: <Widget>[
      SliverToBoxAdapter(
        child: Container(
          child: Text('This is a single widget'),
        ),
      )
    ],
  ),
);
Add image from network in Flutter
Image.network(
  'https://placeimg.com/640/480/any',
)
Concatenate two list in Flutter
List<String> _fruits = ["apple", "banana"];
List<String> _vegetables = ["Potato", "carrot"];

_fruits.addAll(_vegetables); //This will join the list

print(_fruits)
Mediz size property
// full screen width and height
double width = MediaQuery.of(context).size.width;
double height = MediaQuery.of(context).size.height;

// height without SafeArea
var padding = MediaQuery.of(context).padding;
double height1 = height - padding.top - padding.bottom;

// height without status bar
double height2 = height - padding.top;

// height without status and toolbar
double height3 = height - padding.top - kToolbarHeight;
Create stateful widget in Flutter
class WidgetName extends StatefulWidget {
  const WidgetName({ super.key });

  @override
  State<WidgetName> createState() => _WidgetNameState();
}

class _WidgetNameState extends State<WidgetName> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(color: const Color(0xFFFFE306));
  }
}
Rounded input button with shadows
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Container(
          color: Colors.blue[500],
          child: Center(
            child: MyWidget(),
          ),
        ),
      ),
    );
  }
}

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Column(
        children: [
          TextField(
            style: TextStyle(height: 1.6),
            cursorColor: Colors.amber,
            decoration: InputDecoration(
              prefixIcon: Icon(Icons.today),
              border: InputBorder.none,
              hintText: 'Enter a search term',
            ),
          ).shadow(),
          TextField(
            style: TextStyle(height: 1.6),
            cursorColor: Colors.amber,
            decoration: InputDecoration(
              prefixIcon: Icon(Icons.today),
              border: InputBorder.none,
              hintText: 'Enter a search term',
            ),
          ).shadow(),
          FlatButton(
            onPressed: null,
            child: Text(
              "Text Button",
              style: TextStyle(color: Colors.white),
            ),
          ).buttonShadow()
        ],
      ),
    );
  }
}

extension ShadowMaker on Widget {
  shadow() {
    return Card(
      margin: EdgeInsets.symmetric(
        vertical: 10.0,
        horizontal: 20.0,
      ),
      elevation: 6,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(35),
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: 10,
          vertical: 5,
        ),
        child: this,
      ),
    );
  }

  buttonShadow() {
    return Card(
      color: Colors.redAccent,
      margin: EdgeInsets.symmetric(
        vertical: 10.0,
        horizontal: 20.0,
      ),
      elevation: 4,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(35),
      ),
      child: Padding(
        padding: const EdgeInsets.symmetric(
          horizontal: 18.0,
        ),
        child: this,
      ),
    );
  }
}
Card rounded
Card(
    elevation: 8,
    shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(8),
    ),
    color: Colors.blue,
    child: Padding(
        padding: const EdgeInsets.all(32.0),
        child:Text("Hello"),
    )
)
Store with Flux pattern
import 'dart:convert';
import 'package:localstorage/localstorage.dart';
import 'EventManager.dart';

class TopicStore {
  final LocalStorage storage = new LocalStorage('settings.json');
  final String storeKey = "NEWS_TOPICS";
  List newsTopics = new List();

  static TopicStore instance = new TopicStore._();

  TopicStore._() {
    //initalizeTopics();
  }

  init() async {
    await _loadFromStore();
  }

  _loadFromStore() async {
    await storage.ready;
    var data = storage.getItem(storeKey);
    if (data != null) {
      newsTopics = jsonDecode(data);
      print("From Topic store .. " + newsTopics.toString());
      EventManager.eventBus.fire(new TopicEvent("loaded", newsTopics));
    }
  }

  _saveToStorage() {
    storage.setItem(storeKey, jsonEncode(newsTopics));
    EventManager.eventBus.fire(new TopicEvent("updated", newsTopics));
  }

  addTopic(String topic) {
    newsTopics.add(topic);
    _saveToStorage();
  }

  removeTopic(int index) {
    newsTopics.removeAt(index);
    _saveToStorage();
  }
}

class TopicEvent {
  String action;
  List topics;
  TopicEvent(this.action, this.topics);
}

import 'package:event_bus/event_bus.dart';

class EventManager {
  static final EventBus eventBus = EventBus();
}
Form with List style
idget _buildUI() {
  return new Scaffold(
    appBar: new AppBar(
      title: new Text("Hello"),
      actions: <Widget>[
        new IconButton(icon: const Icon(Icons.save), onPressed: () {})
      ],
    ),
    body: new Column(
      children: <Widget>[
        new ListTile(
          leading: const Icon(Icons.person),
          title: new TextField(
            decoration: new InputDecoration(
              hintText: "Name",
            ),
          ),
        ),
        new ListTile(
          leading: const Icon(Icons.phone),
          title: new TextField(
            decoration: new InputDecoration(
              hintText: "Phone",
            ),
          ),
        ),
        new ListTile(
          leading: const Icon(Icons.email),
          title: new TextField(
            decoration: new InputDecoration(
              hintText: "Email",
            ),
          ),
        ),
        const Divider(
          height: 1.0,
        ),
        new ListTile(
          leading: const Icon(Icons.label),
          title: const Text('Nick'),
          subtitle: const Text('None'),
        ),
        new ListTile(
          leading: const Icon(Icons.today),
          title: const Text('Birthday'),
          subtitle: const Text('February 20, 1980'),
        ),
        new ListTile(
          leading: const Icon(Icons.group),
          title: const Text('Contact group'),
          subtitle: const Text('Not specified'),
        )
      ],
    ),
  );
}
Tab View
DefaultTabController(
    length: 3,
    child: Scaffold(
      appBar: AppBar(
        elevation: 0,
        bottom: TabBar(indicatorSize: TabBarIndicatorSize.label, tabs: [
          Tab(
            child: Align(
              alignment: Alignment.center,
              child: Text("APPS"),
            ),
          ),
          Tab(
            child: Align(
              alignment: Alignment.center,
              child: Text("MOVIES"),
            ),
          ),
          Tab(
            child: Align(
              alignment: Alignment.center,
              child: Text("GAMES"),
            ),
          ),
        ]),
      ),
      body: TabBarView(children: [
        Icon(Icons.apps),
        Icon(Icons.movie),
        Icon(Icons.games),
      ]),
    ),
  );
Buttons Rounded
RaisedButton(
    onPressed: () {},
    color: Colors.amber,
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
    child: Text("Click This"),
  );

  FlatButton(
    onPressed: () {},
    color: Colors.amber,
    shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
    child: Text("Click This"),
  );

  GestureDetector(
    onTap: () {},
    child: Container(
      width: 100,
      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(20), color: Colors.blue),
      child: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Text(
          "Click",
          textAlign: TextAlign.center,
        ),
      ),
    ),
  );

  RaisedButton(
    onPressed: () {},
    color: Colors.amber,
    shape: RoundedRectangleBorder(
        side: BorderSide(color: Colors.red, width: 2),
        borderRadius: BorderRadius.circular(10)),
    child: Text("Click This"),
  );
Blur
Widget _buildUI() {
  return Stack(
    fit: StackFit.expand,
    children: [
      FlutterLogo(),
      Center(
        child: ClipRect(
          child: BackdropFilter(
            filter: ImageFilter.blur(
              sigmaX: 10.0,
              sigmaY: 10.0,
            ),
            child: Container(
              width: 200,
              height: 200,
              alignment: Alignment.center,
              child: Text('Hi Frost'),
            ),
          ),
        ),
      ),
    ],
  );
}

//Full screen blur
Widget _buildUI() {
  return Stack(
    fit: StackFit.expand,
    children: [
      FlutterLogo(),
      Center(
        child: BackdropFilter(
          filter: ImageFilter.blur(
            sigmaX: 10.0,
            sigmaY: 10.0,
          ),
          child: Container(
            alignment: Alignment.center,
            child: Text('Hi Frost'),
          ),
        ),
      ),
    ],
  );
}
Textfield in rows
Widget _buildUI() {
  return Row(
    children: [
      Flexible(
        child: new TextField(
          decoration: InputDecoration(
            labelText: "First Name",
          ),
        ),
      ),
      Flexible(
        child: new TextField(
          decoration: InputDecoration(
            labelText: "Last Name",
          ),
        ),
      )
    ],
  );
}
Background image on scafold
class BgImage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Material App',
      home: Scaffold(
        resizeToAvoidBottomInset: false,
        appBar: AppBar(
          title: Text('Background'),
        ),
        body: Container(
          constraints: BoxConstraints.expand(),
          decoration: BoxDecoration(
              image: DecorationImage(
                  image: AssetImage("images/app_bg.jpg"), fit: BoxFit.cover)),
                  //image: NetworkImage(
                //"https://encrypted-tbn0.gstatic.com/images?q=tbn%3AANd9GcQXDPKPH6IhukvE5AAx-L3_bwhAIKfiV0fI64LrZBqfLg4XclKGe6kjOZqbNpfQ4jRx5QRkguEDMGxxqjTk5QGUa8FrgEJS&usqp=CAU"),
          child: TextField(
            decoration: InputDecoration(fillColor: Colors.amber, filled: true),
          ),
        ),
      ),
    );
  }
}
Wrap widgets
class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Wrap(
      direction: Axis.horizontal,
      alignment: WrapAlignment.center,
      spacing: 20.0,
      runSpacing: 20.0,
      children: [
        
        Container(child: Text("1").center(), color: Colors.red, width: 100, height: 100),
        Container(child: Text("1").center(), color: Colors.red, width: 100, height: 100),
        Container(child: Text("1").center(), color: Colors.red, width: 100, height: 100),
        Container(child: Text("1").center(), color: Colors.red, width: 100, height: 100),

      ],
    );
  }
}

extension UIHelper on Widget {
  Widget center() {
    return Center(child: this);
  }
}
Map of objects
List<Map> categories = [
  {'name': 'Cats', 'iconPath': 'images/cat.png'},
  {'name': 'Dogs', 'iconPath': 'images/dog.png'},
  {'name': 'Bunnies', 'iconPath': 'images/rabbit.png'},
  {'name': 'Parrots', 'iconPath': 'images/parrot.png'},
  {'name': 'Horses', 'iconPath': 'images/horse.png'}
];

List<Map> drawerItems=[
  {
    'icon': FontAwesomeIcons.paw,
    'title' : 'Adoption'
  },
  {
    'icon': Icons.mail,
    'title' : 'Donation'
  },
  {
    'icon': FontAwesomeIcons.plus,
    'title' : 'Add pet'
  },
  {
    'icon': Icons.favorite,
    'title' : 'Favorites'
  },
  {
    'icon': Icons.mail,
    'title' : 'Messages'
  },
  {
    'icon': FontAwesomeIcons.userAlt,
    'title' : 'Profile'
  },
];
Text Style helpers
Widget _buildHeadingSub(mainString, subString) {
  return SizedBox(
    // color: Colors.red,
    width: double.infinity,
    child: Column(
      children: <Widget>[
        Text(
          mainString,
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontSize: 20,
            fontWeight: FontWeight.bold,
          ),
        ),
        SizedBox(
          height: 2.0,
        ),
        Text(
          subString,
          textAlign: TextAlign.center,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            fontSize: 15,
            color: Colors.grey[600],
          ),
        ),
      ],
    ),
  );
}

// Leading Icon Header
Widget _buildUI() {
  return Row(
    mainAxisAlignment: MainAxisAlignment.start,
    children: <Widget>[
      Icon(Icons.star, size: 50),
      Expanded(
        child: Container(
          color: Colors.green,
          child: Padding(
            child: Text("Some big heading here"),
            padding: EdgeInsets.all(10.0),
          ),
        ),
      ),
    ],
  );
}
Column Row Tips
//Limiting the width of Column itself, use SizedBox
SizedBox(
  width: 100, // set this
  child: Column(...),
)

//Limiting width of children inside Column, without hardcoding values
Row(
  children: <Widget>[
    Expanded(
      flex: 3, // takes 30% of available width 
      child: Child1(),
    ),
    Expanded(
      flex: 7, // takes 70% of available width  
      child: Child2(),
    ),
  ],
)

//Limiting width of children inside Column, with hardcoding values.
Row(
  children: <Widget>[
    SizedBox(
      width: 100, // hard coding child width
      child: Child1(),
    ),
    SizedBox(
      width: 200, // hard coding child width
      child: Child2(),
    ),
  ],
)
Launcher
import 'package:url_launcher/url_launcher.dart';

void _showUrl() {
  _launch('http://www.nandiraju.com');
}

void _showEmail() {
  _launch('mailto:[email protected]');
}

void _showTelephone() {
  _launch('tel:999-999-9999');
}

void _showSms() {
  _launch('sms:999-999-9999');
}

void _launch(String urlString) async {
  if(await canLaunch(urlString)) {
    await launch(urlString);
  } else {
    throw 'Could not launch Url';
  }
}
Bottom Sheet
void _showBottom() {
showModalBottomSheet<void>(
    context: context,
    builder: (BuildContext context) {
    return new Container(
        padding: new EdgeInsets.all(15.0),
        child: new Row(
        mainAxisAlignment:  MainAxisAlignment.center,
        children: <Widget>[
            new Text('Widgets here', style: new TextStyle(color: Colors.red, fontWeight: FontWeight.bold),),
            new RaisedButton(onPressed: () => Navigator.pop(context), child: new Text('Close'),)
        ],
        ),
    );  
    }
);
  
@override
Widget build(BuildContext context) {
    return new Scaffold(
        appBar: new AppBar(
        title: new Text('Name here'),
        ),
        body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Center(
            child: new Column(
            children: <Widget>[
                new Text('Add Widgets Here'),
                new RaisedButton(onPressed: _showBottom, child: new Text('Click me'),)
            ],
            ),
        )
        ),
    );
}
SnackBar
import 'package:flutter/material.dart';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

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

class _State extends State<MyApp> {
  
  final GlobalKey<ScaffoldState> _scaffoldstate = new GlobalKey<ScaffoldState>();
  
  void _showbar() {
    _scaffoldstate.currentState.showSnackBar(new SnackBar(content: new Text('Hello world')));
  }
  
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      key: _scaffoldstate,
      appBar: new AppBar(
        title: new Text('Name here'),
      ),
      body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Center(
          child: new Column(
            children: <Widget>[
              new Text('Add Widgets Here'),
              new RaisedButton(onPressed: _showbar, child: new Text('Click me'),)
            ],
          ),
        )
      ),
    );
  }
}
Date Picker
import 'package:flutter/material.dart';
import 'dart:async';

void main() {
  runApp(new MaterialApp(
    home: new MyApp(),
  ));
}

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

class _State extends State<MyApp> {
  
  String _value = '';
  
  Future _selectDate() async {
    DateTime picked = await showDatePicker(
        context: context,
        initialDate: new DateTime.now(),
        firstDate: new DateTime(2016),
        lastDate: new DateTime(2099)
    );
   if(picked != null) setState(() => _value = picked.toString());     
  }
  
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text('Name here'),
      ),
      body: new Container(
        padding: new EdgeInsets.all(32.0),
        child: new Center(
          child: new Column(
            children: <Widget>[
              new Text(_value),
              new RaisedButton(onPressed: _selectDate, child: new Text('Click me'),)
            ],
          ),
        )
      ),
    );
  }
}
Dropdown example
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyDropDown()
    );
  }
}

class MyDropDown extends StatefulWidget {
  @override
  _MyDropDownState createState() => _MyDropDownState();
}

class _MyDropDownState extends State<MyDropDown> {
  final List<String> subjects = ["Computer Science", "Biology", "Math"];

  String selectedSubject = "Biology";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        padding: EdgeInsets.all(32),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            DropdownButton<String>(
              value: selectedSubject,
              onChanged: (value){
                setState(() {
                  selectedSubject = value;
                });
              },
              items: subjects.map<DropdownMenuItem<String>>((value){
                return DropdownMenuItem(
                  child: Text(value),
                  value: value,
                );
              }).toList(),
            ),

            Text(selectedSubject, style: TextStyle(fontSize: 36, fontWeight: FontWeight.w900),)

          ],
        ),
      ),
    );
  }
}
Form creation example
import 'package:flutter/material.dart';

class FormScreen extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return FormScreenState();
  }
}

class FormScreenState extends State<FormScreen> {
  String _name;
  String _email;
  String _password;
  String _url;
  String _phoneNumber;
  String _calories;

  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  Widget _buildName() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Name'),
      maxLength: 10,
      validator: (String value) {
        if (value.isEmpty) {
          return 'Name is Required';
        }

        return null;
      },
      onSaved: (String value) {
        _name = value;
      },
    );
  }

  Widget _buildEmail() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Email'),
      validator: (String value) {
        if (value.isEmpty) {
          return 'Email is Required';
        }

        if (!RegExp(
                r"[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?")
            .hasMatch(value)) {
          return 'Please enter a valid email Address';
        }

        return null;
      },
      onSaved: (String value) {
        _email = value;
      },
    );
  }

  Widget _buildPassword() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Password'),
      keyboardType: TextInputType.visiblePassword,
      validator: (String value) {
        if (value.isEmpty) {
          return 'Password is Required';
        }

        return null;
      },
      onSaved: (String value) {
        _password = value;
      },
    );
  }

  Widget _builURL() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Url'),
      keyboardType: TextInputType.url,
      validator: (String value) {
        if (value.isEmpty) {
          return 'URL is Required';
        }

        return null;
      },
      onSaved: (String value) {
        _url = value;
      },
    );
  }

  Widget _buildPhoneNumber() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Phone number'),
      keyboardType: TextInputType.phone,
      validator: (String value) {
        if (value.isEmpty) {
          return 'Phone number is Required';
        }

        return null;
      },
      onSaved: (String value) {
        _url = value;
      },
    );
  }

  Widget _buildCalories() {
    return TextFormField(
      decoration: InputDecoration(labelText: 'Calories'),
      keyboardType: TextInputType.number,
      validator: (String value) {
        int calories = int.tryParse(value);

        if (calories == null || calories <= 0) {
          return 'Calories must be greater than 0';
        }

        return null;
      },
      onSaved: (String value) {
        _calories = value;
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Form Demo")),
      body: Container(
        margin: EdgeInsets.all(24),
        child: Form(
          key: _formKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              _buildName(),
              _buildEmail(),
              _buildPassword(),
              _builURL(),
              _buildPhoneNumber(),
              _buildCalories(),
              SizedBox(height: 100),
              RaisedButton(
                child: Text(
                  'Submit',
                  style: TextStyle(color: Colors.blue, fontSize: 16),
                ),
                onPressed: () {
                  if (!_formKey.currentState.validate()) {
                    return;
                  }

                  _formKey.currentState.save();

                  print(_name);
                  print(_email);
                  print(_phoneNumber);
                  print(_url);
                  print(_password);
                  print(_calories);

                  //Send to API
                },
              )
            ],
          ),
        ),
      ),
    );
  }
}
Container Style
Widget getUIWidget() {
  return Container(
      margin: EdgeInsets.all(10.0),
      width: 200.0,
      height: 100.0,
      decoration: new BoxDecoration(
        color: Colors.blue,
        borderRadius: BorderRadius.circular(10.0),
        border: Border.all(
          color: Colors.white,
          width: 1.0,
        ),
        boxShadow: [
          BoxShadow(
            blurRadius: 6,
            offset: Offset(4, 4),
            color: Color(0xff333333).withOpacity(.4),
            spreadRadius: -2,
          )
        ],
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          Expanded(
            flex: 1,
            child: Container(
              child: Icon(
                Icons.access_alarm,
                color: Colors.white,
                size: 50.0,
              ),
              margin: EdgeInsets.all(4.0),
            ),
          ),
          Padding(
            padding: EdgeInsets.all(5.0),
            child: Text('Hello World!'),
          ),
          SizedBox(height: 10.0)
        ],
      ));
}
Life cycle of component
class _MyComponentState extends State<MyComponent> {
  @override
  void initState() {
    // this method is called before the first build
    super.initState();
  }

  @override
  void didUpdateWidget(MyComponent oldWidget) {
    // this method IS called when parent widget is rebuilt
    super.didUpdateWidget(oldWidget);
  }

  @override didChangeDependencies() {
    // called when InheritedWidget updates
    // read more here https://api.flutter.dev/flutter/widgets/InheritedWidget-class.html
    super.didChangeDependencies();
  }

  @override
  void dispose() {
    // called after widget was unmounted from widget tree
    super.dispose();
  }
}
Object to JSON
class User {
    String displayName;
    String photoUrl;

    User({this.displayName, this.photoUrl});

    User.fromJson(Map<String, dynamic> json)
      : displayName = json['displayName'],
        photoUrl = json['photoUrl'];

    Map<String, dynamic> toJson() {
      return {
        'displayName': displayName,
        'photoUrl': photoUrl,
      };
    }
}

final user = User.fromJson(json.decode(jsonString));
json.encode(user.toJson());
List Data Structures
void main() {
  //print(_showDateFormat());

  var oneTask = new Task("A", _genId());
  _addToMap(oneTask);
  _addToList(oneTask);
  oneTask = new Task("B", _genId());
  _addToMap(oneTask);
  _addToList(oneTask);

  for (final oneTask in taskList) {
    print(oneTask.name);
  }

//   int foundIndex = taskList.indexWhere((taskItem) {
//     taskItem.name.startsWith('B');
//   });

  print("Index found at .. ");

  print(_findInList("A").id);

//   details.forEach((k, v) {
//     print(k);
//     print(v.name);
//   });
}

class Task {
  String name;
  int id;
  Task(this.name, this.id);
}

// DateTime stuff
_showDateFormat() {
  var currDt = DateTime.now();
//   var newDt = DateFormat.yMMMEd().format(currDt);
//   return newDt;
}

// List stuff -------------------------
var taskList = new List<Task>();
_addToList(Task task) {
  taskList.add(task);
}

Task _findInList(String query) {
  return taskList.singleWhere((taskItem) => taskItem.name == query);
}

_removeFromList(int id) {
  taskList.removeWhere((item) => item.id == id);
}

// Map stuff -------------------------
var details = new Map<int, Task>();
int _genId() {
  return new DateTime.now().millisecondsSinceEpoch;
}

_addToMap(Task task) {
  details[task.id] = task;
}
Arrays
final length = items.length;

final newItems = items..addAll(otherItems);

final allEven = items.every((item) => item % 2 == 0);

final filled = List<int>.filled(3, 42);

final even = items.where((n) => n % 2 == 0).toList();

final found = items.firstWhere((item) => item.id == 42);

final index = items.indexWhere((item) => item.id == 42);

final flat = items.expand((_) => _).toList();

final mapped = items.expand((item) => [item + 1]).toList();

items.forEach((item) => print(item));

items.asMap().forEach((index, item) => print('$item, $index'));

final includes = items.contains(42);

final indexOf = items.indexOf(42);

final joined = items.join(',');

final newItems = items.map((item) => item + 1).toList();

final item = items.removeLast();

items.add(42);

final reduced = items.fold({}, (acc, item) {
  acc[item.id] = item;
  return acc;
});

final reversed = items.reversed;

items.removeAt(0);

final slice = items.sublist(15, 42);

final hasOdd = items.any((item) => item % 2 == 0);

items.sort((a, b) => a - b);

items.replaceRange(15, 42, [1, 2, 3]);

items.insert(0, 42);
Platform check
import 'dart:io' show Platform;

if (Platform.isIOS) {
  doSmthIOSSpecific();
}

if (Platform.isAndroid) {
  doSmthAndroidSpecific();
}
Grid Ways
Widget build(BuildContext context) {
    return GridView(
      gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
        maxCrossAxisExtent: 200.0,
        crossAxisSpacing: 10.0,
        mainAxisSpacing: 10.0,
        childAspectRatio: 1,
      ),
      children: <Widget>[
        _getTile(),
        _getTile(),
        _getTile(),
        _getTile(),
      ],
    );
  }


GridView.count(...)

GridView.count(
  crossAxisCount: 2,
  children: <Widget>[
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
  ],
)
GridView.builder(...)

GridView.builder(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemBuilder: (_, index) => FlutterLogo(),
  itemCount: 4,
)
GridView(...)

GridView(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  children: <Widget>[
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
  ],
)
GridView.custom(...)

GridView.custom(
  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  childrenDelegate: SliverChildListDelegate(
    [
      FlutterLogo(),
      FlutterLogo(),
      FlutterLogo(),
      FlutterLogo(),
    ],
  ),
)
GridView.extent(...)

GridView.extent(
  maxCrossAxisExtent: 400,
  children: <Widget>[
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
    FlutterLogo(),
  ],
)
Text Styles
Text(
  "Text With Styles",
  style: TextStyle(
    color: Colors.grey[800],
    fontWeight: FontWeight.bold,
    fontSize: 30,
    shadows: [
      Shadow(
        color: Colors.grey[100],
        blurRadius: 1.0,
        offset: Offset(2.0, 2.0),
      ),
      Shadow(
        color: Colors.grey[600],
        blurRadius: 1.0,
        offset: Offset(-2.0, 2.0),
      ),
    ],
  ),
)
FAB Extended
floatingActionButton: FloatingActionButton.extended(
    onPressed: () {},
    icon: Icon(Icons.save),
    label: Text("Save"),
)
Card Style 1
Widget getUICard() {
  return SizedBox(
      height: 300.00,
      child: Card(
        elevation: 8.0,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(8.0),
        ),
        child: Column(
          children: <Widget>[
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                "New York",
                style: TextStyle(
                  fontSize: 20.0,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            Padding(
              padding: const EdgeInsets.all(16.0),
              child: Text(
                  "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book."),
            ),
          ],
        ),
      ));
}
Stack Layout
Stack(
  children: <Widget>[
    BottomWidget(),
    MiddleWidget(),
    TopWidget(),
  ],
)

Widget getUIWidget() {
  return Stack(
    children: <Widget>[
      // Max Size
      Container(
        color: Colors.green,
      ),
      Container(
        color: Colors.blue,
        height: 200.0,
        width: 200.0,
      ),
      Align(
        //Wrap around align to algin
        alignment: Alignment.topCenter,
        child: Container(
          color: Colors.red,
          height: 150.0,
          width: 150.0,
        ),
      ),
      Positioned(
        right: 40.0,
        top: 40.0,
        child: Container(
          color: Colors.orange,
          height: 150.0,
          width: 150.0,
        ),
      )
    ],
  );
}
Convert HexColor to Flutter color
Color colorConvert(String color) {
  color = color.replaceAll("#", "");
  if (color.length == 6) {
    return Color(int.parse("0xFF" + color));
  } else if (color.length == 8) {
    return Color(int.parse("0x" + color));
  }
}
PageView with item builder
Widget getUIWidget() {
  return PageView.builder(
    itemBuilder: (context, position) {
      return Container(
        color: position % 2 == 0 ? Colors.pink : Colors.cyan,
      );
    },
  );
}

// Outside build method
PageController controller = PageController();
// Inside build method
PageView(
  controller: controller,
  children: <Widget>[
    // Add children
  ],
)
PageView in Flutter
Widget getUIWidget() {
  return PageView(
    children: <Widget>[
      Container(
        color: Colors.pink,
      ),
      Container(
        color: Colors.cyan,
      ),
      Container(
        color: Colors.deepPurple,
      ),
    ],
  );
}
Flutter Logging
var logger = Logger();
logger.d("Debug message");
logger.e("Error message");
logger.i("Info message");
logger.v("Verbose message");
logger.w("Warning message");
logger.wtf("WTF message");
Seperated ListView
ListView.separated(
      itemBuilder: (context, position) {
        return ListItem();
      },
      separatorBuilder: (context, position) {
        return SeparatorItem();
      },
      itemCount: itemCount,
)
Form with Rows and icons
Widget getUIWidget() {
  return Row(
    children: [
      Flexible(
        child: new TextField(
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.print),
            labelText: "First Name",
          ),
        ),
      ),
      SizedBox(width: 10.0),
      Flexible(
        child: new TextField(
          decoration: InputDecoration(
            prefixIcon: Icon(Icons.email),
            labelText: "Last Name",
          ),
        ),
      )
    ],
  );
}
SVG Load
#dependencies:
#flutter_svg: ^0.17.2
SvgPicture.asset("images/someimage.svg",color: Colors.amber,)
SvgPicture.network("https://mightymamma.com/someimage.svg")
Styled border
Widget getUIWidget() {
  return Container(
    padding: EdgeInsets.all(10),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(10), bottomRight: Radius.circular(10)),
        border: Border.all(color: Colors.blueAccent, width: 2)),
    child: Text('Simple Border'),
  );
}
Linear Gradient Container
Widget getUIWidget() {
  return Container(
    width: double.infinity,
    height: double.infinity,
    decoration: BoxDecoration(
        gradient: LinearGradient(
      colors: [Colors.blue, Colors.green],
      begin: Alignment.topLeft,
      end: Alignment.bottomRight,
    )),
  );
}
Radial Gradient Container
Widget getUIWidget() {
  return Container(
    child: Text("Hello"),
    width: 300.0,
    height: 300.0,
    decoration: BoxDecoration(
        gradient: RadialGradient(
      colors: [Colors.blue, Colors.blue[900]],
    )),
  );
}
Flutter Row with elements at ends
Row(
    children: [
      Container(height: 100, width: 100, color: Colors.red),
      Spacer(),
      Container(height: 100, width: 100, color: Colors.green)
    ],
  )
ListBuilder
ListView.builder(
  itemCount: 10,
  physics: BouncingScrollPhysics(),
  itemBuilder: (context, index) {
    return ListTile(
      title: Text("Long Text"),
    );
  }
)
Change text style in flutter
Text(
    'Here will be the text',
    style: TextStyle(
        color: Colors.blue,
        fontWeight: FontWeight.bold,
        fontSize: 30.0,
        fontStyle: FontStyle.italic,
        fontFamily: 'cursive'
    ),
),
Add border to container in flutter
Container(
    decoration: BoxDecoration(
        border: Border.all(
            width: 2.0,
            color: Colors.blue,
            style: BorderStyle.solid
        ),
    ),
    child: Text(
        'Hello world'
    ),
),
Add border radius to container in flutter
Container(
    margin: EdgeInsets.all(30.0),
    padding: EdgeInsets.all(20.0),
    decoration: BoxDecoration(
        borderRadius: BorderRadius.all(
            Radius.circular(10),
        ),
        color: Colors.red,
    ),
    child: Text(
        'Hello world'
    ),
),
Add margin to container in Flutter
Container(
    margin: EdgeInsets.all(40.0),
    child: Text(
        'Hello world'
    ),
),
Add padding to container in Flutter
Container(
    padding: EdgeInsets.all(50.0),
    child: Text(
        'Hello world'
    ),
),
Simple stateless widget in Flutter
import 'package:flutter/material.dart'

class WidgetName extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'App title',
      home: Container(
        child: Text('Hello World'),
      ),
    );
  }
}
Add border to widget in Flutter
//ADD BORDER TO ALL SIDES
Container(
  decoration: BoxDecoration(
    border: Border.all(
      color: Colors.red,
      width: 3.0,
    ),
  ),
)

//ADD BORDER TO SPECIFIC SIDES
Container(
  decoration: BoxDecoration(
    border: Border(
      left: BorderSide(
        color: Colors.red,
        width: 3.0,
      ),
      top: BorderSide(
        color: Colors.blue,
        width: 3.0,
      ),
    ),
  ),
)
Add box shadow to container in flutter
Container(
  height: 200.0,
  width: 200.0,
  decoration: const BoxDecoration(
    color: Color(0xFFffffff),
    boxShadow: [
      BoxShadow(
        color: Colors.grey,
        blurRadius: 15.0, // soften the shadow
        spreadRadius: 5.0, //extend the shadow
        offset: Offset(
          5.0, // Move to right 5  horizontally
          5.0, // Move to bottom 5 Vertically
        ),
      )
    ],
  ),
  child: const Text("Hello world"),
),
Hide title from BottomNavigationBar in Flutter
BottomNavigationBar(
    showSelectedLabels: false,
    showUnselectedLabels: false,
    items: <BottomNavigationBarItem> []
);
Converting class objects to JSON string in Flutter
class Employee {
  final String name;
  final String email;

  Employee(this.name, this.email);

  Employee.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}

//Now CONVERT SIMPLE JSON TO FLUTTER OBJECT 
Map employeeMap = jsonDecode(jsonString);
var employee = Employee.fromJson(employeeMap);

//CONVERT FLUTTER OBJECT TO SIMPLE JSON STRING
String json = jsonEncode(employee);