Notes App Using Flutter



In this tutorial, we'll be creating a Notes application using Flutter,

Notes app are essential tools for keeping track of tasks and staying organized. Our app creates a scrollable notes sections, allowing users to input Notes via a text field. Notes are dynamically displayed within containers. Users can scroll through the list as needed. A reset option is available to clear all notes and start afresh. By the end of this tutorial, you'll have a functional Notes app that you can run on both Android and iOS devices.


Source Code for the main.dart file




Add the following Code inside your main.dart file :


             
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:notes/getdata.dart';
import 'package:notes/showdata.dart';


Future< void> main() async {
    WidgetsFlutterBinding.ensureInitialized();
    await Firebase.initializeApp();
    runApp(const MyApp());
}

class MyApp extends StatelessWidget {
    const MyApp({super.key});

    @override
    Widget build(BuildContext context) {
    return MaterialApp(
        theme: ThemeData.dark().copyWith(textTheme: TextTheme(bodyMedium: TextStyle(color: Colors.white))),
        home: Showdata(),
    );
    }
}
                
             
            


Source Code for the show.dart file




Add the following Code inside your show.dart file :


             
import 'dart:math';

import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:notes/getdata.dart';

class Showdata extends StatefulWidget {
    const Showdata({super.key});

    @override
    State< Showdata> createState() => _ShowdataState();
}



class _ShowdataState extends State< Showdata> {

    final _firestore=FirebaseFirestore.instance;
    bool upd=false;


    void confirmdelete(id){
    showDialog(
        context: context,
        builder: (BuildContext context){
            return AlertDialog(
            title: Text('Confirm Delete'),
            content: Text('Are you sure you want to delete this data?'),
            actions: [
                TextButton(
                onPressed: () {
                    Navigator.of(context).pop(); // Close the dialog
                },
                child: Text('Cancel'),
                ),
                TextButton(
                onPressed: () async{
                    Navigator.of(context).pop(); // Close the dialog
                    // Call your delete function here
                    // Perform the delete operation

                    try {
                    CollectionReference collection = _firestore.collection(
                        'message');

                    DocumentReference docref = collection.doc(id);

                    await docref.delete();
                    } catch (e) {
                    print("Error deleting document: $e");
                    }

                },
                child: Text('Delete'),
                ),
            ],
            );
        });
    }


    @override
    Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('My Notes',style: TextStyle(fontSize: 20),),
        ),
        body: StreamBuilder< QuerySnapshot< Map< String, dynamic>>>(
        stream: _firestore.collection('message').orderBy('time').snapshots(),
        builder: (context,snapshot){
            if(!snapshot.hasData)
            {
                return Center(
                child:CircularProgressIndicator(
                    backgroundColor: Colors.blueAccent,
                )
                );
            }
            else if(snapshot.hasError){
            return Text('Error: ${snapshot.error}');
            }
            else{
            final messages=snapshot.data?.docs.reversed;
            List< Widget> messagetextwidget=[];

            for(var message in messages!)
                {
                final titletext=message.data()['title'];
                final timetext=message.data()['time'];
                final messagetext=message.data()['message'];
                final color=message.data()['color'];
                final docId=message.id;



                final messagewidget=MessageNote(
                    title:titletext,
                    time:timetext,
                    message:messagetext,
                    id:docId,
                    deletedata:(String? id) => confirmdelete(id),
                    color:color
                );
                messagetextwidget.add(messagewidget);
                }
            return ListView(
                reverse: false,
                padding: EdgeInsets.symmetric(vertical: 20.0,horizontal: 10.0),
                children:messagetextwidget ,
            );
            }
        },
        ),
        floatingActionButton: FloatingActionButton(
        onPressed: (){
            Navigator.push(context,MaterialPageRoute(builder: (context)=>Getdata(
            upd: false,
            )));
        },
        backgroundColor: Colors.grey.shade800,

        child: Icon(Icons.add,color: Colors.white,size: 30,),
        ),
    );
    }
}


class MessageNote extends StatelessWidget {
    MessageNote({required this.title,required this.time,required this.message,this.id,this.deletedata,this.color});

    final String title;
    final String time;
    final String message;
    final String? id;
    final Function(String?)? deletedata;
    final String? color;


    Color randomcolorgenerate(){
        final random=Random();
        return Color.fromARGB(
        255,
        150 + random.nextInt(106), // Red component between 150 and 255
        150 + random.nextInt(106), // Green component between 150 and 255
        150 + random.nextInt(106), // Blue component between 150 and 255
        );
    }



    Color hexToColor(String hexCode) {
        final buffer = StringBuffer();
        if (hexCode.length == 6 || hexCode.length == 7) {
        buffer.write('ff');
        }
        buffer.write(hexCode.replaceFirst('#', ''));
        return Color(int.parse(buffer.toString(), radix: 16));
    }

    @override
    Widget build(BuildContext context) {
    return Padding(
        padding: const EdgeInsets.all(6.0),
        child: GestureDetector(
        onTap: (){
            Navigator.push(context,MaterialPageRoute(builder: (context)=>Getdata(
                upd: true,
            title: title,
            message: message,
            time: time,
            docId:id
            )));
        },
        child: Container(
            decoration: BoxDecoration(
            borderRadius: BorderRadius.circular(20),
            color: hexToColor(color!),
            ),
            padding: EdgeInsets.all(19),
            child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
                Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                    ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: 240),
                    child: Text(
                        title==""?"Undefined":title,
                        style: TextStyle(
                            fontSize: 23,
                            color: Colors.black,
                            fontWeight: FontWeight.bold
                        ),
                        maxLines: 1,
                        overflow: TextOverflow.ellipsis,
                    ),
                    ),
                    SizedBox(height: 15,),
                    ConstrainedBox(
                    constraints: BoxConstraints(maxWidth: 240),
                    child: Text(
                        message==""?"Undefined":message,
                        softWrap: true,
                        style: TextStyle(
                            color: Colors.black,
                            fontSize: 16,
                            fontWeight: FontWeight.w600
                        ),
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                    ),

                    ),
                    SizedBox(height: 16,),
                    Text(
                    time,
                    style: TextStyle(
                        color: Colors.black.withOpacity(0.6),
                        fontSize: 11,
                        fontWeight: FontWeight.w500,
                        fontStyle:FontStyle.italic
                    ),
                    )
                ],
                ),
                Center(
                child:IconButton(
                    onPressed: (){
                    deletedata!(id);
                    },
                    icon:Icon(Icons.delete,size: 25,color: Colors.grey.shade700,),
                ),
                )
            ],
            ),
        ),
        ),
    );
    }
}

                
             
            


Source Code for the getdata.dart file




Add the following Code inside your getdata.dart file :


             
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:intl/intl.dart';

class Getdata extends StatefulWidget {
    Getdata({this.title,this.message,this.time,required this.upd,this.docId});

    String? title;
    String? message;
    String? time;
    bool upd;
    String? docId;

    @override
    State< Getdata> createState() => _GetdataState();
}



class _GetdataState extends State< Getdata> {

    final _firestore=FirebaseFirestore.instance;
    late final titlecontroller=TextEditingController();
    final messagecontroller=TextEditingController();
    String? date;


    String randomColorGenerate() {
    final random = Random();
    final red = 150 + random.nextInt(106);
    final green = 150 + random.nextInt(106);
    final blue = 150 + random.nextInt(106);
    final color = Color.fromARGB(255, red, green, blue);
    return '#' +
        red.toRadixString(16).padLeft(2, '0') +
        green.toRadixString(16).padLeft(2, '0') +
        blue.toRadixString(16).padLeft(2, '0');
    }



    void updatedata() async{

    print(widget.title==titlecontroller.text);
    if(widget.title==titlecontroller.text && widget.message==messagecontroller.text)
        {
        showDialog(
            context: context,
            builder: (context) {
                return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    AlertDialog(
                    title: Center(
                        child: Text('Error', style: TextStyle(fontSize: 30),)),
                    content: Column(
                        children: [
                        Icon(Icons.cancel, color: Colors.red, size: 130,),
                        SizedBox(height: 12,),
                        Center(child: Text('Update Some data Before Updating',
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 25, fontWeight: FontWeight
                                .bold),)),
                        ],
                    ),
                    actions: [
                        TextButton(onPressed: () {
                        Navigator.pop(context);
                        }, child: Text('Ok'))
                    ],
                    ),
                ],
                );
            }
        );

        }
    else{

        try {

        await _firestore.collection('message').doc(
            widget.docId).update({
            'title': titlecontroller.text,
            'time': date,
            'message': messagecontroller.text
        }).whenComplete(() {

            Navigator.pop(context);
            showDialog(
                context: context,
                builder: (context) {
                return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                    AlertDialog(
                        title: Center(child: Text('Data Saved', style: TextStyle(
                            fontSize: 30),)),
                        content: Column(
                        children: [
                            Icon(Icons.check_circle, color: Colors.green,
                            size: 130,),
                            SizedBox(height: 12,),
                            Center(child: Text(
                            'Your Data has been Updated Successfully',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: 25, fontWeight: FontWeight.bold),)),
                        ],
                        ),
                        actions: [
                        TextButton(onPressed: () {
                            Navigator.pop(context);
                        }, child: Text('Ok'))
                        ],
                    ),
                    ],
                );
                }

            );


        });

        }

        catch(e){

        showDialog(
            context: context,
            builder: (context) {
                return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    AlertDialog(
                    title: Center(
                        child: Text('Error', style: TextStyle(fontSize: 30),)),
                    content: Column(
                        children: [
                        Icon(Icons.cancel, color: Colors.red, size: 130,),
                        SizedBox(height: 12,),
                        Center(child: Text('Try Again',
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 25, fontWeight: FontWeight
                                .bold),)),
                        ],
                    ),
                    actions: [
                        TextButton(onPressed: () {
                        Navigator.pop(context);
                        }, child: Text('Ok'))
                    ],
                    ),
                ],
                );
            }
        );
        }
    }

    }

    Future< void> savedata() async{
    CollectionReference users=_firestore.collection('message');
    try {
        if (titlecontroller.text == "" && messagecontroller.text == "") {
        showDialog(
            context: context,
            builder: (context) {
                return Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                    AlertDialog(
                    title: Center(
                        child: Text('Error', style: TextStyle(fontSize: 30),)),
                    content: Column(
                        children: [
                        Icon(Icons.cancel, color: Colors.red, size: 130,),
                        SizedBox(height: 12,),
                        Center(child: Text('Enter Some Data Before Saving',
                            textAlign: TextAlign.center,
                            style: TextStyle(fontSize: 25, fontWeight: FontWeight
                                .bold),)),
                        ],
                    ),
                    actions: [
                        TextButton(onPressed: () {
                        Navigator.pop(context);
                        }, child: Text('Ok'))
                    ],
                    ),
                ],
                );
            }
        );
        }
        else {


        await users.add({
            'title': titlecontroller.text,
            'message': messagecontroller.text,
            'time': date!,
            'color':randomColorGenerate()
        }).whenComplete(() {
            Navigator.pop(context);

            showDialog(
                context: context,
                builder: (context) {
                return Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                    AlertDialog(
                        title: Center(child: Text('Data Saved', style: TextStyle(
                            fontSize: 30),)),
                        content: Column(
                        children: [
                            Icon(Icons.check_circle, color: Colors.green,
                            size: 130,),
                            SizedBox(height: 12,),
                            Center(child: Text(
                            'Your Data has been saved Successfully',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                                fontSize: 25, fontWeight: FontWeight.bold),)),
                        ],
                        ),
                        actions: [
                        TextButton(onPressed: () {
                            Navigator.pop(context);
                        }, child: Text('Ok'))
                        ],
                    ),
                    ],
                );
                }

            );
        });
        }
    }
    catch(e){
        print('error ${e}');
        showDialog(
            context: context,
            builder: (context) {
            return AlertDialog(
                title: Text('Error'),
                content: Column(
                children: [
                    Icon(Icons.cancel, color: Colors.red, size: 24,),
                    SizedBox(height: 12,),
                    Text('Try Again'),
                ],
                ),
                actions: [
                TextButton(onPressed: () {
                    Navigator.pop(context);
                }, child: Text('Ok'))
                ],
            );
            }
        );
    }
    }

    void Currentdate(){
    DateTime now=DateTime.now();

    String formatteddate=DateFormat('dd MMM,yyyy HH:mm:ss').format(now);
    date= formatteddate;
    }

    @override
    void initState() {
    // TODO: implement initState
    super.initState();
    Currentdate();

    if(widget.upd==true)
        {
        setState(() {
            titlecontroller.text='${widget.title}';
            messagecontroller.text='${widget.message}';
            date=widget.time;
        });
        }
    }
    Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
        title: Text('Add Notes',style: TextStyle(fontSize: 20),),
        actions: [
            TextButton(onPressed: (){

            if(widget.upd==false) {
                savedata();
            }
            else{
                updatedata();
            }
            }, child: Text(
                (widget.upd)?'Update data' :'Save data',
            )
            ),
            TextButton(onPressed: (){
            Navigator.pop(context);
            }, child: Text('Close'))
        ],
        ),
        body: Padding(
        padding: const EdgeInsets.all(8.0),
        child: Column(
            children: [
            SizedBox(height: 16,),
            Padding(
                padding: const EdgeInsets.all(8.0),
                child: Container(
                padding: EdgeInsets.symmetric(horizontal: 12),
                decoration: BoxDecoration(
                    color: Color(0xFF4D4D4D),
                    borderRadius: BorderRadius.circular(30)
                ),
                child: Row(
                    children: [
                    Text('Title:',style: TextStyle(fontSize: 20),),
                    SizedBox(width: 7,),
                    Expanded(
                        child: TextField(
                        controller: titlecontroller,
                        decoration: InputDecoration(
                            hintText: "Enter title......",
                            border: InputBorder.none
                        ),
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: 20,
                            fontWeight: FontWeight.bold
                        ),
                        onChanged: (value){
                            print(titlecontroller.text);
                        },
                        ),
                    )
                    ],
                ),
                ),
            ),
            SizedBox(height: 12,),
            Container(
                padding: EdgeInsets.symmetric(horizontal: 16),
                child: Align(
                alignment: Alignment.centerRight,
                child: Text(
                    date!,
                    style: TextStyle(
                    fontSize: 14,
                    color: Colors.white
                    ),
                ),
                ),
            ),
            SizedBox(height: 16,),
            Expanded(
                child: Container(
                height: double.infinity,
                padding: EdgeInsets.all(20),

                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(20),
                    color: Color(0xFF4D4D4D),
                ),
                child: TextField(
                    controller: messagecontroller,
                    keyboardType: TextInputType.multiline,
                    maxLines: null,
                    textInputAction: TextInputAction.newline,
                    decoration: InputDecoration(
                    hintText: "Enter message....",
                    border: InputBorder.none,

                    ),
                    style: TextStyle(
                    color: Colors.white,
                    fontSize: 20
                    ),

                ),
                ),
            ),

            ],
        ),
        ),
    );
    }
}


                
             
            


The Output is shown below :





Contact Us

REACH US

SERVICES

  • CODING
  • ON-LINE PREPARATION
  • JAVA & PYTHON

ADDRESS

B-54, Krishna Bhawan, Parag Narain Road, Near Butler Palace Colony Lucknow
Contact:+ 919839520987
Email:info@alexsir.com