Quiz app using flutter with firebase

Created simple quiz app using flutter with Firebase



In this blog I have created a quiz app using flutter with Firebase(FirebaseFirestore). 


Screenshot







First connect your app with Firebase.


Code
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      theme: ThemeData(
        primarySwatch: Colors.blue,

        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: QuizHomePage(),
    );
  }
}
class QuizHomePage extends StatefulWidget {
  @override
  _QuizHomePageState createState() => _QuizHomePageState();
}

class _QuizHomePageState extends State<QuizHomePage> {
var db=FirebaseFirestore.instance.collection("question");
List<QuizData> questions=[];
bool isLoading=true;
@override
void initState(){
 try {
    db.snapshots().listen((event) {
      questions.clear();
      for (var item in event.docs) {
        if(mounted){
          setState(() {
            Map<String,dynamic> data=item.data();
            var d=QuizData(question: data["question"], 
            answer: data["answer"], options: data["options"]);
            questions.add(d);
            isLoading=false;
          
          });
        }
        
      }
     });
 } catch (e) {
 }
  super.initState();

}


  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Quiz app demo"),
      

      ),
      body:isLoading?Center(child: 
      CircularProgressIndicator(),): QuizStart(data: questions,),
    );
  }
}

class QuizStart extends StatefulWidget {
  final List<QuizData> data;
  QuizStart({this.data});
  @override
  _QuizStartState createState() => _QuizStartState();
}

class _QuizStartState extends State<QuizStart> {
  int count=0;
  String selectedAns="";
  int correctAns=0;
  
  @override
  void initState() {

    super.initState();
  }
  var questionStyle=TextStyle(fontSize: 18,fontWeight: FontWeight.w700);
  void prev(){
    if(count==0)
    return;
    else
    if(mounted){
      setState(() {
        count--;
      });
    }
  }
  void next(){
    if(count==widget.data.length-1)
    return;
    else
    if(mounted){
      setState(() {
        count++;
      });
    }
  }
  void _check(){
    if(selectedAns==widget.data[count].answer[0]){
      print("Correct ans");
      if(mounted){
        setState(() {
          correctAns++;
        });
      }
    next();
    }else{
      next();
      print("wrong ans");
    }
  }

  @override
  Widget build(BuildContext context) {
    return widget.data.length==0?  
          Center(child:Text("No quiz data")):ListView(
      shrinkWrap: true,
      physics: ClampingScrollPhysics(),
       children: [

         //Next and Prev
         Row(
           crossAxisAlignment: CrossAxisAlignment.start,
           mainAxisAlignment: MainAxisAlignment.spaceAround,
           children: [

             RaisedButton(onPressed: (){prev();},
             child:Text("Prev"),color: Colors.red[200],),
            RaisedButton(onPressed: (){next();},
            child:Text("Next"), color: Colors.blue[200],)
           ],
         ),




         //Question
          Container(
          margin: EdgeInsets.all(10),
          child: Text(widget.data[0].question,style: questionStyle,),
          
            ),
        //Option
        Container(
          height: MediaQuery.of(context).size.height*0.4,
          child: ListView.builder(
            shrinkWrap: true,
            physics: ClampingScrollPhysics(),
            itemCount: widget.data[count].options.length,
            itemBuilder: (context, index) => Ink(
              color: widget.data[count].options[index]==selectedAns?Colors.red:Colors.transparent,
              child: ListTile(
              
              onTap: (){
                if(mounted){
                  setState(() {
                    selectedAns=widget.data[count].options[index];
                  });
                }
              },
              title: Text(widget.data[count].options[index]),

            ),),),
        )
        
        //Check the answer
        ,Container(
          margin: EdgeInsets.fromLTRB(MediaQuery.of(context).size.width*0.60200),
          child: RaisedButton(onPressed: (){
            _check();
          },
          color: Colors.blue,
          child: Text("Submit"),),
        )


       ],
      
    );
  }
}



class QuizData{
    String question;
    List<dynamic> answer;
    List<dynamic> options;
    QuizData({@required this.question,@required this.answer,@required this.options});


}





PUBG


My one of the favorite Youtube channel of PUBG in Nepal is Mr Red Dot. You can also check it out.






Comments

Popular Posts