online software programming courses

Flutter crash course

Code for app_colors.dart

import 'dart:ui';

final Color background = Color(0xFFfafafc);
final Color sliverBackground = Color(0xFFfafafc);
final Color menu1Color=Color(0xFFf9d263);
final Color menu2Color= Color(0xFFf2603d);
final Color menu3Color= Color(0xFF04abe6);
final Color tabVarViewColor=Color(0xFFfdfdfd);
final Color starColor=Color(0xFFfdc746);
final Color subTitleText=Color(0xFFc5c4ca);
final Color loveColor=Color(0xFF00ace6);
final Color audioBluishBackground=Color(0xFfdee7fa);
final Color audioBlueBackground= Color(0xFF04abe7);
final Color audioGreyBackground=Color(0xFFf2f2f2);

 

Code for audio_file.dart

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AudioFile extends StatefulWidget {
  final AudioPlayer advancedPlayer;
  final String audioPath;
  const AudioFile({Key key, this.advancedPlayer, this.audioPath}) : super(key: key);

  @override
  _AudioFileState createState() => _AudioFileState();
}

class _AudioFileState extends State<AudioFile> {
  Duration _duration = new Duration();
  Duration _position = new Duration();
  bool isPlaying=false;
  bool isPaused=false;
  bool isRepeat=false;
  Color color= Colors.black;
  List<IconData> _icons = [
    Icons.play_circle_fill,
    Icons.pause_circle_filled,
  ];

  @override
  void initState(){
    super.initState();
    this.widget.advancedPlayer.onDurationChanged.listen((d) {setState(() {
      _duration=d;
    });});
    this.widget.advancedPlayer.onAudioPositionChanged.listen((p) {setState(() {
      _position=p;
    });});

    this.widget.advancedPlayer.setUrl(this.widget.audioPath);
    this.widget.advancedPlayer.onPlayerCompletion.listen((event) {
      setState(() {
        _position = Duration(seconds: 0);
        if(isRepeat==true){
          isPlaying=true;
        }else{

        isPlaying=false;
        isRepeat=false;
        }
      });
    });
  }

  Widget btnStart() {
    return IconButton(
        padding: const EdgeInsets.only(bottom: 10),
        icon:isPlaying==false?Icon(_icons[0], size:50, color:Colors.blue):Icon(_icons[1], size:50, color:Colors.blue),
        onPressed: (){
          if(isPlaying==false) {
            this.widget.advancedPlayer.play(this.widget.audioPath);
            setState(() {
              isPlaying = true;
            });
          }else if(isPlaying==true){
            this.widget.advancedPlayer.pause();
            setState(() {
              isPlaying=false;
            });
          }
        },
    );
  }

  Widget btnFast() {
    return
      IconButton(
        icon:   ImageIcon(
          AssetImage('img/forward.png'),
          size: 15,
          color: Colors.black,
        ),
        onPressed: () {
          this.widget.advancedPlayer.setPlaybackRate(playbackRate: 1.5);
        },
      );
  }
  Widget btnSlow() {
    return IconButton(
      icon:   ImageIcon(
        AssetImage('img/backword.png'),
        size: 15,
        color: Colors.black,
      ),
      onPressed: () {
        this.widget.advancedPlayer.setPlaybackRate(playbackRate: 0.5);

      },
    );
  }
  Widget btnLoop() {
    return IconButton(
        icon:   ImageIcon(
          AssetImage('img/loop.png'),
          size: 15,
          color: Colors.black,
        )
    );
  }
  Widget btnRepeat() {
    return IconButton(
      icon: ImageIcon(
        AssetImage('img/repeat.png'),
        size: 15,
        color:color,
      ),
      onPressed: (){
        if(isRepeat==false){
          this.widget.advancedPlayer.setReleaseMode(ReleaseMode.LOOP);
          setState(() {
            isRepeat=true;
            color=Colors.blue;
          });
        }else if(isRepeat==true){
          this.widget.advancedPlayer.setReleaseMode(ReleaseMode.RELEASE);
          color=Colors.black;
          isRepeat=false;
        }
      },
    );
  }

  Widget slider() {
    return Slider(
        activeColor: Colors.red,
        inactiveColor: Colors.grey,
        value: _position.inSeconds.toDouble(),
        min: 0.0,
        max: _duration.inSeconds.toDouble(),
        onChanged: (double value) {
          setState(() {
            changeToSecond(value.toInt());
            value = value;
          });});
  }

  void changeToSecond(int second){
    Duration newDuration = Duration(seconds: second);
    this.widget.advancedPlayer.seek(newDuration);
  }

  Widget loadAsset() {
    return
      Container(
          child:Row(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children:[
                btnRepeat(),
                btnSlow(),
                btnStart(),
                btnFast(),
                btnLoop()
              ])
      );
  }
  @override
  Widget build(BuildContext context) {
    return
      Container(child:
      Column(
      children: [
        Padding(
          padding: const EdgeInsets.only(left: 20, right: 20),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,

            children: [
              Text(_position.toString().split(".")[0], style: TextStyle(fontSize: 16),),

              Text(_duration.toString().split(".")[0], style: TextStyle(fontSize: 16),),
            ],
          ),
        ),

        slider(),
        loadAsset(),
      ],
    )

    );
  }
}

 

Code for detail_audio_page.dart

import 'package:audioplayers/audioplayers.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:audio/app_colors.dart' as AppColors;

import 'audio_file.dart';
class DetailAudioPage extends StatefulWidget {
  final booksData;
  final int index;
  const DetailAudioPage({Key key, this.booksData, this.index}) : super(key: key);

  @override
  _DetailAudioPageState createState() => _DetailAudioPageState();
}

class _DetailAudioPageState extends State<DetailAudioPage> {
  AudioPlayer advancedPlayer;

  @override
  void initState(){
    super.initState();
    advancedPlayer= AudioPlayer();
  }

  @override
  Widget build(BuildContext context) {
    final double screenHeight=MediaQuery.of(context).size.height;
    final double screenWidth=MediaQuery.of(context).size.width;

    return Scaffold(
      backgroundColor: AppColors.audioBluishBackground,
      body: Stack(
            children: [
              Positioned(
                  top:0,
                  left: 0,
                  right: 0,
                  height: screenHeight/3,
                  child: Container(
                  color:AppColors.audioBlueBackground

              )),
              Positioned(
                  top:0,
                  left: 0,
                  right: 0,
                  child: AppBar(
                    leading: IconButton(
                      icon:Icon(Icons.arrow_back_ios,),
                      onPressed: (){
                        Navigator.of(context).pop();
                        advancedPlayer.stop();
                        },
                    ),

                    actions: [
                      IconButton(
                        icon:Icon(Icons.search,),
                        onPressed: (){},
                      )
                    ],
                    backgroundColor: Colors.transparent,
                    elevation: 0.0,
              )),
              Positioned(
                  left: 0,
                  right: 0,
                  top: screenHeight*0.2,
                  height: screenHeight*0.36,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(40),
                    color:Colors.white,

                    ),
                  child:Column(
                    children: [
                      SizedBox(height: screenHeight*0.1,),
                      Text("THE WATER LIFE",
                      style: TextStyle(
                        fontSize: 30,
                        fontWeight: FontWeight.bold,
                        fontFamily: "Avenir"
                      ),
                      ),
                      Text("Hazard Hyatt", style:TextStyle(
                        fontSize: 20
                      ),),
                      AudioFile(advancedPlayer:advancedPlayer, audioPath:this.widget.booksData[this.widget.index]["audio"]),
                    ],
                  )

              )),
              Positioned(
                  top:screenHeight*0.12,
                  left: (screenWidth-150)/2,
                  right: (screenWidth-150)/2,
                  height: screenHeight*0.16,
                  child: Container(
                    decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      border: Border.all(color:Colors.white, width: 2),
                      color:AppColors.audioGreyBackground,

                    ),
                    child: Padding(
                      padding: const EdgeInsets.all(20),
                      child: Container(
                        decoration: BoxDecoration(
                          //borderRadius: BorderRadius.circular(20),
                          shape: BoxShape.circle,
                          border: Border.all(color:Colors.white, width: 5),
                          image:DecorationImage(
                            image:AssetImage(this.widget.booksData[this.widget.index]["img"]),
                            fit:BoxFit.cover
                          )
                        ),
                      ),
                    ),
              )

              )
            ],
      ),
    );
  }
}

 

code for main.dart

import 'package:audio/detail_audio_page.dart';
import 'package:flutter/material.dart';

import 'my_home_page.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Audio App',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(

        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

 

Code for my_home_page.dart

import 'dart:convert';

import 'package:audio/detail_audio_page.dart';
import 'package:flutter/cupertino.dart';
import 'package:audio/app_colors.dart' as AppColors;
import 'package:flutter/material.dart';

import 'my_tabs.dart';
class MyHomePage extends StatefulWidget {
  const MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> with SingleTickerProviderStateMixin {
  List popularBooks;
  List books;
  ScrollController _scrollController;
  TabController _tabController;
  ReadData() async {
   await DefaultAssetBundle.of(context).loadString("json/popularBooks.json").then((s){
      setState(() {
       popularBooks = json.decode(s);
      });
    });
   await DefaultAssetBundle.of(context).loadString("json/books.json").then((s){
     setState(() {
       books = json.decode(s);
     });
   });
  }

  @override
  void initState(){
    super.initState();
    _tabController = TabController(length: 3, vsync: this);
    _scrollController = ScrollController();
    ReadData();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      color: AppColors.background,
          child: SafeArea(
            child: Scaffold(
              body: Column(
                children: [
                  Container(
                    margin: const EdgeInsets.only(left: 20, right: 20),
                    child:  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      ImageIcon(AssetImage("img/menu.png"), size:24, color:Colors.black),
                      Row(
                        children: [
                          Icon(Icons.search),
                          SizedBox(width: 10,),
                          Icon(Icons.notifications),
                        ],
                      )
                    ],
                  ),
                  ),
                  SizedBox(height: 20,),
                  Row(
                    children: [
                      Container(
                        margin: const EdgeInsets.only(left: 20),
                        child: Text("Popular Books", style: TextStyle(fontSize: 30))

                      )
                    ],
                  ),
                  SizedBox(height: 20,),
                  Container(
                    height: 180,
                    child: Stack(
                     children: [

                      Positioned(
                        top:0,
                        left: -20,
                        right: 0,
                        child: Container(
                    height: 180,
                    child: PageView.builder(
                        controller: PageController(viewportFraction: 0.8),
                        itemCount: popularBooks==null?0:popularBooks.length,
                        itemBuilder: (_, i){
                      return Container(
                        height: 180,
                        width: MediaQuery.of(context).size.width,
                        margin: const EdgeInsets.only(right: 10),
                        decoration: BoxDecoration(
                          borderRadius: BorderRadius.circular(15),
                          image:DecorationImage(
                            image:AssetImage(popularBooks[i]["img"]),
                            fit:BoxFit.fill,
                          )
                        ),
                      );
                    }),
                  )
                      )
                      ]

                    )
                  ),
                  Expanded(child: NestedScrollView(
                    controller: _scrollController,
                    headerSliverBuilder: (BuildContext context, bool isScroll){

                      return[
                        SliverAppBar(
                          pinned: true,
                            backgroundColor:AppColors.sliverBackground,
                          bottom: PreferredSize(
                            preferredSize: Size.fromHeight(50),
                            child: Container(
                              margin: const EdgeInsets.only(bottom: 20, left: 10),
                              child: TabBar(
                                indicatorPadding: const EdgeInsets.all(0),
                                indicatorSize: TabBarIndicatorSize.label,
                                labelPadding: const EdgeInsets.only(right: 10),
                                controller: _tabController,
                                isScrollable: true,
                                indicator: BoxDecoration(
                                  borderRadius: BorderRadius.circular(10),
                                  boxShadow: [
                                    BoxShadow(
                                      color:Colors.grey.withOpacity(0.2),
                                      blurRadius: 7,
                                      offset: Offset(0, 0),
                                    )
                                  ]
                                ),
                                tabs: [
                                  AppTabs(color:AppColors.menu1Color, text:"New"),
                                  AppTabs(color:AppColors.menu2Color, text:"Popular"),
                                  AppTabs(color:AppColors.menu3Color, text:"Trending"),
                                ],
                              ),
                            ),
                          ),
                        )
                      ];
                    },
                    body: TabBarView(
                      controller: _tabController,
                      children: [
                        ListView.builder(
                            itemCount: books==null?0:books.length,
                            itemBuilder: (_,i){
                          return
                            GestureDetector(
                              onTap:(){
                                Navigator.push(context,
                                MaterialPageRoute(builder: (context)=>DetailAudioPage(booksData:books, index:i))
                                );
                              },

                            child:Container(
                            margin: const EdgeInsets.only(left:20, right: 20,top:10, bottom: 10),
                            child: Container(
                              decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(10),
                                color:AppColors.tabVarViewColor,
                                boxShadow: [
                                  BoxShadow(
                                    blurRadius: 2,
                                    offset: Offset(0, 0),
                                    color:Colors.grey.withOpacity(0.2),
                                  )
                                ]
                              ),
                              child: Container(
                                padding: const EdgeInsets.all(8),
                                child: Row(
                                  children: [
                                    Container(
                                      width: 90,
                                      height: 120,
                                      decoration: BoxDecoration(
                                          borderRadius: BorderRadius.circular(10),
                                          image: DecorationImage(
                                            image: AssetImage(books[i]["img"]),
                                          )
                                      ),
                                    ),
                                    SizedBox(width: 10,),
                                    Column(
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: [
                                        Row(
                                          children: [
                                            Icon(Icons.star, size:24, color:AppColors.starColor),
                                            SizedBox(width: 5,),
                                            Text(books[i]["rating"], style: TextStyle(
                                                color:AppColors.menu2Color
                                            ),),
                                          ],
                                        ),
                                        Text(books[i]["title"], style: TextStyle(fontSize: 16, fontFamily: "Avenir", fontWeight: FontWeight.bold),),
                                        Text(books[i]["text"], style: TextStyle(fontSize: 16, fontFamily: "Avenir", color:AppColors.subTitleText),),
                                        Container(
                                          width: 60,
                                          height: 20,
                                          decoration: BoxDecoration(
                                            borderRadius: BorderRadius.circular(3),
                                            color:AppColors.loveColor,
                                          ),
                                          child:Text("Love", style: TextStyle(fontSize: 10, fontFamily: "Avenir", color:Colors.white),),
                                          alignment: Alignment.center,
                                        )
                                      ],
                                    )
                                  ],
                                ),
                              ),
                            ),
                          )
                            );
                        }),
                        Material(
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundColor: Colors.grey,
                            ),
                            title: Text("Content"),
                          ),

                        ),
                        Material(
                          child: ListTile(
                            leading: CircleAvatar(
                              backgroundColor: Colors.grey,
                            ),
                            title: Text("Content"),
                          ),

                        ),
                      ],

                    ),
                  ))
                ],
              ),
            ),
          ),
    );
  }
}

 

Code for my_tabs.dart

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AppTabs extends StatelessWidget {
  final Color color;
  final String text;
  const AppTabs({Key key, this.color, this.text}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return   Container(
      width:120,
      height: 50,
      child: Text(
        this.text, style: TextStyle(color:Colors.white, fontSize: 20),

      ),
      alignment: Alignment.center,

      decoration: BoxDecoration(
          borderRadius: BorderRadius.circular(10),
          color:this.color,
          boxShadow: [
            BoxShadow(
              color:Colors.grey.withOpacity(0.3),
              blurRadius: 7,
              offset: Offset(0, 0),
            )
          ]
      ),
    );
  }
}