Flutter Cookbook

Feb 16, 2021 5 min read
Flutter Cookbook

This cookbook contains recipes that demonstrate how to solve common problems while writing Flutter apps.

Setup

Create project

flutter create project_name

With organisation name

flutter create --org domain.org_name.project_name

Eg: flutter create --org dev.codepur.firstapp

Verify setup status

flutter doctor

Hello Flutter

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello Flutter!',
      home: Material(
        child: Center(
          child: Text('Hello Flutter'),
        ),
      ),
    );
  }
}

Widgets

Stateless Widget

import 'package:flutter/material.dart';

class MyNameWidget extends StatelessWidget {
  MyNameWidget({Key key @required this.name}) : super(key: key);

  final String name;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('Hello, $name'),
    );
  }
}

Using meta & default params in constructor

import 'package:flutter/material.dart';

class PersonWidget extends StatelessWidget {
  PersonWidget({
    @required this.name,
    this.language = 'English',
  });

  final String name;
  final String language;

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Text('$name $language'),
    );
  }
}

Stateful Widget

Gestures

GestureDetector(
  onTap: (){},
  onLongPress: _onLongPress,
  child: Text('Tap me'),
);
Great! Next, complete checkout for full access to Codepur.
Welcome back! You've successfully signed in.
You've successfully subscribed to Codepur.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info has been updated.
Your billing was not updated.