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

DSA in C# | Data Structure and Algorithm using C#

  DSA in C# |  Data Structure and Algorithm using C#: Lecture 1: Introduction to Data Structures and Algorithms (1 Hour) 1.1 What are Data Structures? Data Structures are ways to store and organize data so it can be used efficiently. Think of data structures as containers that hold data in a specific format. Types of Data Structures: Primitive Data Structures : These are basic structures built into the language. Example: int , float , char , bool in C#. Example : csharp int age = 25;  // 'age' stores an integer value. bool isStudent = true;  // 'isStudent' stores a boolean value. Non-Primitive Data Structures : These are more complex and are built using primitive types. They are divided into: Linear : Arrays, Lists, Queues, Stacks (data is arranged in a sequence). Non-Linear : Trees, Graphs (data is connected in more complex ways). Example : // Array is a simple linear data structure int[] number...

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...

Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025

 Top 50 Most Asked MERN Stack Interview Questions and Answers for 2025 Now a days most of the IT Company asked NODE JS Question mostly in interview. I am creating this article to provide help to all MERN Stack developer , who is in doubt that which type of question can be asked in MERN Stack  then they can learn from this article. I am Shiva Gautam,  I have 15 Years of experience in Multiple IT Technology, I am Founder of Shiva Concept Solution Best Programming Institute with 100% Job placement guarantee. for more information visit  Shiva Concept Solution 1. What is the MERN Stack? Answer : MERN Stack is a full-stack JavaScript framework using MongoDB (database), Express.js (backend framework), React (frontend library), and Node.js (server runtime). It’s popular for building fast, scalable web apps with one language—JavaScript. 2. What is MongoDB, and why use it in MERN? Answer : MongoDB is a NoSQL database that stores data in flexible, JSON-like documents. It...