Skip to main content

Most Important Flutter Widgets Code snippet | Learn Flutter by Code

 Create Complete quiz app using flutter app with timer :

import 'dart:async';

import 'package:flutter/material.dart';


class quizApp extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return MaterialApp(

      home: quizAppScreen(),

    );

  }

}


class quizAppScreen extends StatefulWidget {

  @override

  quizAppScreenState createState() => quizAppScreenState();

}


class quizAppScreenState extends State<quizAppScreen> {

  String? _selectedValue1;

  String? _selectedValue2;

  String? _selectedValue3;


  int _secondsRemaining = 20;

  late Timer _timer;


  @override

  void initState() {

    super.initState();

    startTimer();

  }


  void startTimer() {

    _timer = Timer.periodic(Duration(seconds: 1), (timer) {

      setState(() {

        if (_secondsRemaining > 0) {

          _secondsRemaining--;

        } else {

          _timer.cancel();

          _timerFinished();

        }});

    });

  }


  @override

  Widget build(BuildContext context) {

    return Scaffold(

        appBar: AppBar(

          title: Text('Quiz App'),

        ),

        body:SingleChildScrollView(

          child:  Column(

            children: [

              Container(

                  margin: EdgeInsets.only(bottom: 20),

                  decoration: BoxDecoration(

                      borderRadius: BorderRadius.circular(50),

                      border: Border.all(width: 2.0, color: Colors.black)

                  ),

                  child: Padding(

                    padding: EdgeInsets.all(20),

                    child:  Text('$_secondsRemaining',

                      style: TextStyle(fontSize: 24),),

                  )

              ),

              Container(

                  child: Column(

                    children: [

                      Text('Q1. What is the capital of France',style: TextStyle(fontSize: 20,),),

                      RadioListTile(

                        title: Text('a) Paris'),

                        value: 'Option 1',

                        groupValue: _selectedValue1,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue1 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('b) London'),

                        value: 'Option 2',

                        groupValue: _selectedValue1,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue1 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('c) Berlin'),

                        value: 'Option 3',

                        groupValue: _selectedValue1,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue1 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Padding(

                          padding: EdgeInsets.all(0),

                          child:Text('d) Perth'),

                        ),

                        value: 'Option 4',

                        groupValue: _selectedValue1,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue1 = value.toString();

                          });

                        },

                      ),

                    ],

                  )

              ),

              Container(

                  margin: EdgeInsets.only(top: 30),

                  child: Column(

                    children: [

                      Padding(padding: EdgeInsets.only(right: 30),

                        child:Text('Q2. Who is the author of the Harry Potter series?',style: TextStyle(fontSize: 20,),),

                      ),

                      RadioListTile(

                        title: Text('a) George R.R. Martin '),

                        value: 'Option 1',

                        groupValue: _selectedValue2,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue2 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('b) Stephen King'),

                        value: 'Option 2',

                        groupValue: _selectedValue2,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue2 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('c) J.K. Rowling'),

                        value: 'Option 3',

                        groupValue: _selectedValue2,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue2 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Padding(

                          padding: EdgeInsets.all(0),

                          child:Text('d) J.R.R. Tolkien'),

                        ),

                        value: 'Option 4',

                        groupValue: _selectedValue2,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue2 = value.toString();

                          });

                        },

                      ),

                    ],

                  )

              ),

              Container(

                  margin: EdgeInsets.only(top: 30),

                  child: Column(

                    children: [

                      Padding(padding: EdgeInsets.only(left: 20),

                        child:Text('Q3. Which planet is known as the Red Planet?',style: TextStyle(fontSize: 20,),),

                      ),

                      RadioListTile(

                        title: Text('a) Mars'),

                        value: 'Option 1',

                        groupValue: _selectedValue3,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue3 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('b) Venus'),

                        value: 'Option 2',

                        groupValue: _selectedValue3,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue3 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Text('c) Jupiter'),

                        value: 'Option 3',

                        groupValue: _selectedValue3,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue3 = value.toString();

                          });

                        },

                      ),

                      RadioListTile(

                        title: Padding(

                          padding: EdgeInsets.all(0),

                          child:Text('d) Saturn'),

                        ),

                        value: 'Option 4',

                        groupValue: _selectedValue3,

                        onChanged: (value) {

                          setState(() {

                            _selectedValue3 = value.toString();

                          });

                        },

                      ),

                    ],

                  )

              ),

            ],

          ),

        )

    );

  }

  void _timerFinished() {

    setState(() {

      _secondsRemaining = 0;

      // Setting seconds to 0

    });

    showDialog(

      context: context,

      builder: (BuildContext context) {

        return AlertDialog(

          content: Text('Oops! time up'),

          actions: <Widget>[

            TextButton(

              onPressed: () {

                Navigator.of(context).pop();

              },

              child: Text('OK'),

            ),

          ],

        );

      },

    );

  }

}

Create Route to navigate into one app page to another app page:

import 'package:flutter/material.dart';

class FirstRoute extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('First Screen'),

      ),

      body: Center(

        child: ElevatedButton(

          child: Text('Click Here'),


          onPressed: () {

            Navigator.push(

              context,

              MaterialPageRoute(builder: (context) => SecondRoute()),

            );

          },

        ),

      ),

    );

  }

}


class SecondRoute extends StatelessWidget {

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text("Second Screen"),

      ),

      body: Center(

        child: ElevatedButton(


          onPressed: () { 

            Navigator.pop(context);

          },

          child: Text('Go back'),

        ),

      ),

    );

  }

}

How to pass data from one screen to another screen:

Code of FirstRoute.dart

import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:helloproject/addition.dart';

class FirstRoute extends StatelessWidget
{
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar:  AppBar(

        title: Text('First Screen'),

      ),
      body:Center(
        child:ElevatedButton(child:Text("click here"),onPressed:(){
               Navigator.push(context, MaterialPageRoute(builder:(context)=>AddWidget(data:"Welcome in second Screen")));
        })
      )
    );
  }
}


Second Screen:

import 'package:flutter/material.dart';

class AddWidget extends StatefulWidget
{
final String data;
const AddWidget({super.key,required this.data});
@override
State<AddWidget> createState() => _SumWidgetState();
}
class _SumWidgetState extends State<AddWidget> {
TextEditingController num1 = TextEditingController();
TextEditingController num2 = TextEditingController();
String result = '';
@override
 Widget build(BuildContext context) {
  return MaterialApp(

      home: Scaffold(

        appBar: AppBar(title: Text('Flutter Checkbox Example'),),

        body:
   Column(
    mainAxisAlignment: MainAxisAlignment.center,
      children: [
          Padding(
          padding: const EdgeInsets.all(15),
          child: TextField(
            controller: num1,
            keyboardType: TextInputType.number,
            decoration: const InputDecoration(labelText: "Enter First Number"),
          ),
        ),
        Padding(
          padding: const EdgeInsets.all(15),
          child: TextField(
            controller: num2,
            keyboardType: TextInputType.number,
            decoration: const InputDecoration(labelText: "Enter Second Number"),
          ),
        ), ElevatedButton(
          onPressed: () {
            setState(() {
              result = (int.parse(num1.text) + int.parse(num2.text)).toString();
            });
          },
          child: Text('Calculate Sum'),
        ),
        Text(result),
        Text(widget.data)
      ]
  )));
 }
}

Flutter Icon Example:

import 'package:flutter/foundation.dart';

import 'package:flutter/material.dart';

class IconExample extends StatefulWidget {

  const IconExample({Key? key}) : super(key: key);

  @override

  State<IconExample> createState() => _IconExampleState();

}

class _IconExampleState extends State<IconExample> {

  String dropdownValue = 'Mango';

  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(title: const Text("DDDD")),

      body: Row(

          mainAxisAlignment: MainAxisAlignment.spaceAround,

          children: <Widget>[

            Icon(Icons.camera_enhance),

            Icon(Icons.camera_front),

            Icon(Icons.camera_rear),

            Icon(Icons.face),

            Icon(Icons.login),

            Icon(Icons.money),

          ]),


    );

  }

}

Create Animation in Flutter:

import 'package:flutter/material.dart';

class HeroAnimation extends StatefulWidget {

  HeroAnimation() : super();



  @override

  _HeroAnimationState createState() => _HeroAnimationState();

}


class _HeroAnimationState extends State<HeroAnimation> {


  Widget _greenRectangle() {

    return Container(

      width: 75,

      height: 75,

      color: Colors.green,

    );

  }


  Widget _detailPageRectangle() {

    return Container(

      width: 150,

      height: 150,

      color: Colors.red,

    );

  }


  @override

  Widget build(BuildContext context) {

    return Scaffold(

      appBar: AppBar(

        title: Text('Welcome'),

      ),

      body: buildDemoWidget(context),

    );

  }


  Widget buildDemoWidget(BuildContext context) {

    return Center(

      child: Column(

        crossAxisAlignment: CrossAxisAlignment.start,

        children: <Widget>[

          SizedBox(

            height: 30.0,

          ),

          ListTile(

            leading: GestureDetector(

              child: Hero(

                tag: 'hero-rectangle',

                child: _greenRectangle(),

              ),

              onTap: () => _gotoDetailsPage(context),

            ),

            title: Text('Tap on the green icon rectangle to analyse hero animation transition.'),

          ),

        ],

      ),

    );

  }


  void _gotoDetailsPage(BuildContext context) {

    Navigator.of(context).push(MaterialPageRoute(

      builder: (ctx) => Scaffold(

        body: Center(

          child: Column(

            mainAxisAlignment: MainAxisAlignment.center,

            children: <Widget>[

              Hero(

                tag: 'hero-rectangle',

                child: _detailPageRectangle(),

              ),

              Text('This is a place where you can see details about the icon tapped at previous page.'),

            ],

          ),

        ),

      ),

    ));

  }

}


Another Example of Animation in Flutter:-

import 'dart:ffi';


import 'package:flutter/animation.dart';

import 'package:flutter/material.dart';

class MyHomePage1 extends StatefulWidget {

  _HomePageState createState() => _HomePageState();

}

class _HomePageState extends State<MyHomePage1> with SingleTickerProviderStateMixin {

  late Animation<double> animation;

  late AnimationController animationController;

  @override

  void initState() {

    super.initState();

    animationController = AnimationController(vsync: this, duration: Duration(milliseconds: 2500));

    animation = CurvedAnimation(parent: animationController, curve: Curves.easeInOut);

    animation.addListener((){

      setState((){

        print (animation.value.toString());

      });

    });

    animation.addStatusListener((status){

      if(status == AnimationStatus.completed){

        animationController.reverse();

      } else if(status == AnimationStatus.dismissed) {

        animationController.forward();

      }

    });

    animationController.forward();

  }

  @override

  Widget build(BuildContext context) {

    return Center(

        child: AnimatedLogo(

          animation: animation,

        )

    );

  }

}


class AnimatedLogo extends AnimatedWidget {

  final Tween<double> _sizeAnimation = Tween<double>(begin: 0.0, end: 500.0);


  AnimatedLogo({Key? key, required Animation<double> animation}) : super(key: key, listenable: animation);


  @override

  Widget build(BuildContext context) {

    final Animation<double> animation = listenable as Animation<double>;

    return Transform.scale(

      scale: _sizeAnimation.evaluate(animation),

      child: FlutterLogo(),

    );

  }

}

Comments

Popular posts from this blog

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java

JDBC Database Connectivity using JSP and Servlet, Database connectivity on Java JDBC:-   JDBC means Java database connectivity, it is used to connect from the front-end(application server) to the back-end(database server) in the case of Java web application. The database provides a set of tables to store records and JDBC will work similarly to the  bridge between the database table and application form. 1)  Class.forName("drivername")  // Manage Drive         Class.formName("com.mysql.jdbc.Driver");  // MYSQL      Class.forName ("oracle.jdbc.driver.OracleDriver"); //Oracle 2)  Manage Connection String     It establish connection from application server to database server, Java provide DriverManage class and getConnection that will return Connection object.    Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","username","password"); 3)  Manage Statement to...