Code examples (page 4)

This page is for code sharing…

Simple layout #016

Here is the code:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

Timer timer;
const refreshSeconds = const Duration(seconds: 10);

class _ExampleState extends State<Example> {
  StreamSubscription<Position> _locationSubscription;
  double latitude = 0;
  double longitude = 0;
  double altitude = 0;
  double speed = 0;
  bool running = false;
  String status = 'Start';
  Stopwatch watch = Stopwatch();

  void getLocation() {
    if (_locationSubscription == null) {
      final positionStream = Geolocator.getPositionStream();
      _locationSubscription = positionStream.handleError((error) {
        _locationSubscription.cancel();
        _locationSubscription = null;
      }).listen((position) => {
            longitude = position.longitude,
            latitude = position.latitude,
            altitude = position.altitude,
            speed = position.speed,
            print(position.toString()),
          });
      _locationSubscription.pause();
    }
    setState(() {
      if (_locationSubscription.isPaused) {
        _locationSubscription.resume();
      } else {
        _locationSubscription.pause();
      }
    });
  }

  dothework(Timer timer) {
    if (watch.isRunning) {
      setState(() {
        getLocation();
      });
    }
  }

  startWatch() {
    setState(() {
      running = true;
      status = 'Stop';
      watch.start();
      timer = Timer.periodic(refreshSeconds, dothework);
    });
  }

  stopWatch() {
    setState(() {
      running = false;
      status = 'Start';
      watch.stop();
    });
  }

  startOrStop() {
    if (!running) {
      startWatch();
    } else {
      stopWatch();
    }
  }

  @override
  Widget build(BuildContext context) {
    // Using geolocator: ^6.1.13 package from
    // https://pub.dev/packages/geolocator/
    // Need to import: import 'package:geolocator/geolocator.dart';
    // Need to import: import 'dart:async';
    return Container(
      decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topRight,
              end: Alignment.bottomLeft,
              colors: [Colors.blue, Colors.red])),
      width: double.infinity,
      height: double.infinity,
      child: SingleChildScrollView(
        child: Center(
          child: Padding(
            padding: const EdgeInsets.all(8.0),
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  height: 90,
                  width: double.infinity,
                  color: Colors.amber.withOpacity(0.8),
                  child: Column(
                    children: [
                      SizedBox(
                        height: 10,
                      ),
                      Text(
                        'Get My Location',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                            fontSize: 50,
                            color: Colors.red,
                            fontWeight: FontWeight.bold),
                      ),
                    ],
                  ),
                ),
                SizedBox(
                  height: 10,
                ),
                Container(
                  height: 250,
                  width: double.infinity,
                  child: Icon(
                    Icons.blur_circular,
                    color: Colors.white,
                    size: 250,
                  ),
                ),
                Container(
                  width: double.infinity,
                  color: Colors.white.withOpacity(0.5),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'Latitude: $latitude',
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  color: Colors.white.withOpacity(0.5),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'Longitude: $longitude',
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  color: Colors.white.withOpacity(0.5),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'Altitude: $altitude',
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
                Container(
                  width: double.infinity,
                  color: Colors.white.withOpacity(0.5),
                  child: Padding(
                    padding: const EdgeInsets.all(8.0),
                    child: Text(
                      'Speed: $speed',
                      style: TextStyle(fontSize: 20),
                    ),
                  ),
                ),
                SizedBox(
                  height: 15,
                ),
                Container(
                  height: 50,
                  width: double.infinity,
                  decoration: BoxDecoration(
                      borderRadius: BorderRadius.circular(20),
                      color: Colors.blue),
                  child: FlatButton(
                    onPressed: () {
                      startOrStop();
                    },
                    child: Text(
                      '$status',
                      style: TextStyle(fontSize: 18),
                    ),
                  ),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

Here is the result:


Simple layout #017

Here is the code:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  //Using   collapsible_sidebar: ^1.0.7+2 from
  //https://pub.dev/packages/collapsible_sidebar/

  String _headline;
  String _selected;
  IconData _selectedIcon;

  List<CollapsibleItem> generateMenuItems() {
    return [
      generateCollapsibleItem('Emergency', Icons.medical_services_rounded),
      generateCollapsibleItem('Camera', Icons.camera),
      generateCollapsibleItem('Alarm', Icons.access_alarm),
      generateCollapsibleItem('Location', Icons.gps_fixed),
      generateCollapsibleItem('Connections', Icons.wifi),
      generateCollapsibleItem('Storage', Icons.storage),
      generateCollapsibleItem('Settings', Icons.settings),
    ];
  }

  CollapsibleItem generateCollapsibleItem(String title, IconData titleIcon) {
    return CollapsibleItem(
      text: title,
      icon: titleIcon,
      onPressed: () => setState(() => {
            _headline = title,
            _selected = _headline,
            _selectedIcon = titleIcon
          }),
      isSelected: false,
    );
  }

  @override
  Widget build(BuildContext context) {
    List<CollapsibleItem> menuItems = generateMenuItems();

    return CollapsibleSidebar(
      toggleTitle: 'Hide menu',
      items: menuItems,
      title: '$_headline',
      body: Container(
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topRight,
              end: Alignment.bottomLeft,
              colors: [Colors.blue, Colors.pink]),
        ),
        child: Center(
          child: Column(
            children: [
              Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    _selectedIcon,
                    color: Colors.white,
                    size: 30,
                  ),
                  Text(
                    '$_headline',
                    style: TextStyle(
                        fontSize: 30,
                        color: Colors.white,
                        fontWeight: FontWeight.bold),
                  ),
                ],
              ),
            ],
          ),
        ),
      ),
      backgroundColor: Colors.amber.withOpacity(0.5),
      selectedTextColor: Colors.limeAccent,
      unselectedTextColor: Colors.black,
      textStyle: TextStyle(fontSize: 15, fontStyle: FontStyle.italic),
      titleStyle: TextStyle(
          fontSize: 20,
          fontStyle: FontStyle.italic,
          fontWeight: FontWeight.bold),
      toggleTitleStyle: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
    );
  }
}

Here is the result:


Simple layout #018

Here is the code:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return Stack(
      children: [
        Container(
          width: double.infinity,
          height: double.infinity,
          child: GridView(
            gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
                childAspectRatio: size.width / size.height,
                crossAxisSpacing: 10,
                mainAxisSpacing: 10), //Width vs height ratio
            children: [
              Container(
                color: Colors.red,
                width: size.width / 2,
                child: Icon(Icons.flight_takeoff),
              ),
              Container(
                color: Colors.green,
                width: size.width / 2,
                height: size.height / 3,
                child: Icon(Icons.flight_sharp),
              ),
              Container(
                color: Colors.blue,
                width: size.width / 2,
                height: size.height / 3,
                child: Icon(Icons.flight_rounded),
              ),
              Container(
                color: Colors.yellow,
                width: size.width / 2,
                height: size.height / 3,
                child: Icon(Icons.flight_land),
              )
            ],
          ),
        ),
        Positioned(
          child: Container(
            width: size.width / 3,
            height: size.height / 3,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(45),
              color: Colors.white,
            ),
            child: Icon(
              Icons.flight,
              size: size.height / size.width * 50,
            ),
          ),
          top: size.height / 3,
          left: size.width / 3,
        ),
      ],
    );
  }
}

Here is the result:


Simple layout #019

Here is the code:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;
    final boxwidth = size.width / 10;
    final boxheight = size.height / 15;

    return Container(
      color: Colors.black,
      child: Column(
        children: [
          Text(
            'Music Box',
            style: TextStyle(
                fontSize: size.height / 20,
                fontWeight: FontWeight.bold,
                color: Colors.white),
          ),
          SizedBox(
            height: size.height / 25,
          ),
          Expanded(
            child: Container(
              width: double.infinity,
              height: double.infinity,
              decoration: BoxDecoration(
                gradient: LinearGradient(
                    begin: Alignment.topRight,
                    end: Alignment.bottomLeft,
                    colors: [Colors.blue, Colors.red]),
              ),
              child: Padding(
                padding: const EdgeInsets.all(8.0),
                child: GridView(
                  shrinkWrap: true,
                  physics: NeverScrollableScrollPhysics(),
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 4,
                      childAspectRatio: size.width / size.height * 2,
                      crossAxisSpacing: 10,
                      mainAxisSpacing: 10), //Width vs height ratio
                  children: [
                    getMusicKey(
                        boxwidth, boxheight, Colors.red, Icons.music_note, 1),
                    getMusicKey(
                        boxwidth, boxheight, Colors.blue, Icons.music_note, 2),
                    getMusicKey(
                        boxwidth, boxheight, Colors.green, Icons.music_note, 3),
                    getMusicKey(boxwidth, boxheight, Colors.yellow,
                        Icons.music_note, 4),
                    getMusicKey(boxwidth, boxheight, Colors.orange,
                        Icons.music_note, 5),
                    getMusicKey(
                        boxwidth, boxheight, Colors.brown, Icons.music_note, 6),
                    getMusicKey(
                        boxwidth, boxheight, Colors.pink, Icons.music_note, 7),
                    getMusicKey(
                        boxwidth, boxheight, Colors.cyan, Icons.music_note, 8),
                    getMusicKey(
                        boxwidth, boxheight, Colors.grey, Icons.music_note, 9),
                    getMusicKey(boxwidth, boxheight, Colors.purple,
                        Icons.music_note, 10),
                    getMusicKey(boxwidth, boxheight, Colors.indigo,
                        Icons.music_note, 11),
                    getMusicKey(
                        boxwidth, boxheight, Colors.teal, Icons.music_note, 12),
                    getMusicKey(boxwidth, boxheight, Colors.limeAccent,
                        Icons.music_note, 13),
                    getMusicKey(boxwidth, boxheight, Colors.lightBlue,
                        Icons.music_note, 14),
                    getMusicKey(boxwidth, boxheight, Colors.pinkAccent,
                        Icons.music_note, 15),
                    getMusicKey(boxwidth, boxheight, Colors.redAccent,
                        Icons.music_note, 16),
                    getMusicKey(boxwidth, boxheight, Colors.grey.shade700,
                        Icons.music_note, 13),
                    getMusicKey(boxwidth, boxheight, Colors.yellow.shade700,
                        Icons.music_note, 14),
                    getMusicKey(boxwidth, boxheight, Colors.red.shade700,
                        Icons.music_note, 15),
                    getMusicKey(boxwidth, boxheight, Colors.pink.shade800,
                        Icons.music_note, 16)
                  ],
                ),
              ),
            ),
          ),
          SizedBox(height: size.height / 50),
          Container(
            //Free asset image from: https://www.istockphoto.com/
            child: Image.asset(
              //added asset image on assets folder
              'assets/column.jpg',
              height: size.height / 8,
            ),
          ),
        ],
      ),
    );
  }
 Container getMusicKey(double boxwidth, double boxheight, Color color,
      IconData icon, int number) {
    return Container(
      decoration:
          BoxDecoration(color: color, borderRadius: BorderRadius.circular(40)),
      width: boxwidth,
      height: boxheight,
      child: InkWell(
        enableFeedback: false,
        onTap: () {
          //Using  assets_audio_player: ^1.4.7+4 from
          // https://pub.dev/packages/assets_audio_player/install
          final assetsAudioPlayer = AssetsAudioPlayer();

          assetsAudioPlayer.open(
            //added mp3 assets on assets folder
            Audio("assets/sound$number.mp3"),
          );
        },
        child: Icon(icon),
      ),
    );
  }
}

Here is the result:


Simple layout #020

Here is the code:

class Example extends StatefulWidget {
  @override
  _ExampleState createState() => _ExampleState();
}

class _ExampleState extends State<Example> {
  // Using confetti: ^0.5.4+1 from
  // https://pub.dev/packages/confetti
  ConfettiController confettiController;
  final assetsAudioPlayer = AssetsAudioPlayer();

  @override
  void initState() {
    super.initState();

    confettiController = new ConfettiController(
      duration: new Duration(seconds: 45),
    );
    confettiController.play();
    assetsAudioPlayer.open(
      //added mp3 assets on assets folder
      Audio("assets/happybday.mp3"),
      playInBackground: PlayInBackground.enabled,
    );
  }

  @override
  Widget build(BuildContext context) {
    final size = MediaQuery.of(context).size;

    return SingleChildScrollView(
      child: Container(
        color: Colors.black,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            SizedBox(
              height: 10,
            ),
            ConfettiWidget(
              confettiController: confettiController,
              blastDirectionality: BlastDirectionality.explosive,
              particleDrag: 0.05,
              emissionFrequency: 0.05,
              numberOfParticles: 70,
              gravity: 0.05,
            ),
            Text(
              'Happy Birthday!!',
              style: TextStyle(
                color: Colors.amber,
                fontSize: size.height / 10,
                fontWeight: FontWeight.bold,
              ),
              textAlign: TextAlign.center,
            ),
            Container(
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(40),
              ),
              child: Image.asset(
                //free image from canva.com
                'assets/happybday.png',
                width: size.width * 0.70,
                height: size.height * 0.70,
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Here is the result:


Create your website with WordPress.com
Get started
%d bloggers like this: