Giter VIP home page Giter VIP logo

flutter_pics's Introduction

flutter_pics

Version 01

The following code snippet creates a MaterialApp widget and displays it on the mobile phone.

main.dart

// I need to import a helper library
//  from flutter to get content on the screen
import 'package:flutter/material.dart';

// Define a 'main' function to run when our app starts
void main(List args) {
  // Create a new text widget to show some text
  //  on the screen
  var app = MaterialApp(
    home: Text('Hi there'),
  );

  // Take that widget and get it on the screen
  runApp(app);
}

Version 02

The following code snippet shows how to create AppBar and FloatingActionButton on the mobile phone.

main.dart

import 'package:flutter/material.dart';

void main(List args) {
  var app = MaterialApp(
    home: Scaffold(
      appBar: AppBar(
        title: Text('Let\' see some images!'),
      ),
      floatingActionButton: FloatingActionButton(
        child: Icon(Icons.add),
        onPressed: () {
          print('Hi there!');
        },
      ),
    ),
  );

  runApp(app);
}

Version 03

The following code snippet shows how to modularize the MaterialApp widget in another class.

main.dart

import 'package:flutter/material.dart';
import 'src/app.dart';

void main(List args) {
  var app = App();

  runApp(app);
}

app.dart

// Import flutter helper library
import 'package:flutter/material.dart';

// Create a class that will be our custom widget
// This class must extend the 'StatelessWidget' base class
class App extends StatelessWidget {
  // We must define a 'build' method that returns
  //  the widgets   that *this* widget will show
  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Let\' see some images!'),
        ),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            print('Hi there!');
          },
        ),
      ),
    );
  }
}

Version 04

The following code snippet shows how to create a StatefulWidget in Flutter.

main.dart

import 'package:flutter/material.dart';
import 'src/app.dart';

void main(List args) {
  runApp(App());
}

app.dart

import 'package:flutter/material.dart';

// Create a StatefulWidget
class App extends StatefulWidget {
  @override
  createState() {
    return AppState();
  }
}

// Change the previous App class to AppState
//  that extends from State
class AppState extends State {
  int counter = 0;

  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Let\' see some images!'),
        ),
        body: Text('${counter}'),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: () {
            setState(() {
              counter++;
            });
          },
        ),
      ),
    );
  }
}

Handle JSON

The following code snippet shows how encode a JSON object into a model which can be used in another app.

import 'dart:convert';

void main() {
  var rawJSON = '{"url": "http://blah.jpg", "id": 1}';
  
  var parsedJSON = json.decode(rawJSON);
  //var imageModel = ImageModel(
  //  parsedJSON['id'], 
  //  parsedJSON['url']
  //);

  var imageModel = ImageModel.fromJSON(parsedJSON);
  print(imageModel.id);
}

class ImageModel {
  int id;
  String url;
  
  ImageModel(this.id, this.url);
  
  ImageModel.fromJSON(parsedJSON) {
    id = parsedJSON['id'];
    url = parsedJSON['url'];
  }
}

Async Process

The following code snippet shows to execute a time taking process which usually returns a Future object.

Option 1

import 'dart:async';

main() {
  print('About to fetch data...');
  
  get('http://mockupurl')
    .then((result) {
      print(result);
    });
}

Future get(String url) {
  return new Future.delayed(
  	new Duration(seconds: 3), () {
      return 'Got the data!';
    }
  );
}

Option 2

import 'dart:async';

main() async {
  print('About to fetch data...');
  
  /*get('http://mockupurl')
    .then((result) {
      print(result);
    });*/
  var result = await get('http://mockupurl');
  
  print(result);
}

Future get(String url) {
  return new Future.delayed(
  	new Duration(seconds: 3), () {
      return 'Got the data!';
    }
  );
}

Version 05

The following code snippet shows a complete program which displays a fake picture from a website - teaches how to make an HTTP call, JSON manipulation and Modeling.

main.dart

import 'package:flutter/material.dart';
import 'src/app.dart';

void main(List args) {
  runApp(App());
}

app.dart

import 'package:flutter/material.dart';
import 'package:http/http.dart' show get;
import 'dart:convert';
import 'models/image_model.dart';
import 'widgets/image_list.dart';

// Create a StatefulWidget
class App extends StatefulWidget {
  @override
  createState() {
    return AppState();
  }
}

// Change the previous App class to AppState
//  that extends from State
class AppState extends State {
  int counter = 0;
  List images = [];

  void fetchImage() async {
    counter++;
    // Make an HTTP request
    var response =
        await get('http://jsonplaceholder.typicode.com/photos/${counter}');

    var imageModel = ImageModel.fromJSON(json.decode(response.body));

    setState(() {
      images.add(imageModel);
    });
  }

  Widget build(context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Let\' see some images!'),
        ),
        body: ImageList(images),
        floatingActionButton: FloatingActionButton(
          child: Icon(Icons.add),
          onPressed: fetchImage,
        ),
      ),
    );
  }
}

image_model.dart

class ImageModel {
  int id;
  String url;
  String title;

  ImageModel(this.id, this.title, this.url);

  //ImageModel.fromJSON(Map parsedJSON) {
  //  id = parsedJSON['id'];
  //  url = parsedJSON['url'];
  //  title = parsedJSON['title'];
  //}

  ImageModel.fromJSON(Map parsedJSON) 
    : id = parsedJSON['id'],
      url = parsedJSON['url'],
      title = parsedJSON['title'];
  
}

image_list.dart

import 'package:flutter/material.dart';
import '../models/image_model.dart';

class ImageList extends StatelessWidget {
  final List images;

  ImageList(this.images);

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
      itemCount: images.length,
      itemBuilder: (context, int index) {
        return buildImage(images[index]);
      },
    );
  }

  Widget buildImage(ImageModel image) {
    return Container(
      decoration: BoxDecoration(
        border: Border.all(
          color: Colors.grey,
        ),
      ),
      padding: EdgeInsets.all(20.0),
      margin: EdgeInsets.all(20.0),
      child: Column(
        children: [
          Padding(
            child: Image.network(image.url),
            padding: EdgeInsets.only(
              bottom: 8.0,
            ),
          ),
          Text(image.title),
        ],
      ),
    );
  }
}

flutter_pics's People

Contributors

yosephabate avatar

Watchers

 avatar James Cloos 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.