DEV Community

Usman Afzal
Usman Afzal

Posted on

Weather App in #flutter.So easy to use hardware sensors to make fun animations.

A pie chart showing 40% responded

Homepage.dart

import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_weatherapp/homepage/extendpage.dart';
import 'package:http/http.dart' as http;

class frontpage extends StatefulWidget {
  const frontpage({Key? key}) : super(key: key);

  @override
  State<frontpage> createState() => _frontpageState();
}

class _frontpageState extends State<frontpage> {
  int x = 0;
  double temp = 0.0;
  String weathercondition = '';
  double temp1 = 0.0;
  String weathercondition1 = '';
  double temp2 = 0.0;
  String weathercondition2 = '';
  List<String> templist = [];
  List<String> weatherlist = [];
  bool _isLoading = false;
  var a, b, c = 0;
  Getweather1() async {
    setState(() {
      _isLoading = true;
    });
    var api =
        'https://api.openweathermap.org/data/2.5/weather?lat=31.5204&lon=74.329376&exclude=hourly,daily&appid=c1975188522ee8a2a6d9fb75013d0958';
    var api1 =
        'https://api.openweathermap.org/data/2.5/weather?lat=48.8566&lon=2.3522&exclude=hourly,daily&appid=c1975188522ee8a2a6d9fb75013d0958';
    var api2 =
        'https://api.openweathermap.org/data/2.5/weather?lat=41.0082&lon=28.9784&exclude=hourly,daily&appid=c1975188522ee8a2a6d9fb75013d0958';
    var responce = await http.get(Uri.parse(api));
    dynamic list = jsonDecode(responce.body);
    var responce1 = await http.get(Uri.parse(api1));
    dynamic list1 = jsonDecode(responce1.body);
    var responce2 = await http.get(Uri.parse(api2));
    dynamic list2 = jsonDecode(responce2.body);
    setState(() {
      temp = list['main']['temp'] - 273.15;
      //x = temp.toInt();
      //temp = x as double;
      a = temp.round();
      weathercondition = list['weather'][0]['main'];
      temp1 = list1['main']['temp'] - 273.15;
      //x = temp1.toInt();
      //temp1 = x as double;
      b = temp1.round();
      weathercondition1 = list1['weather'][0]['main'];
      temp2 = list2['main']['temp'] - 273.15;
      //x = temp2.toInt();
      //temp2 = x as double;
      c = temp2.round();
      weathercondition2 = list2['weather'][0]['main'];
      templist = [a.toString(), b.toString(), c.toString()];
      weatherlist = [weathercondition, weathercondition1, weathercondition2];
      _isLoading = false;
    });
  }

  final foregroundImages = [
    'assets/lahore1.png',
    'assets/france.png',
    'assets/turkey.png'
  ];
  final backgroundImages = [
    'assets/lahorebg.png',
    'assets/france-bg.jpg',
    'assets/turkeybg.png'
  ];
  final texts = ['Lahore', 'Paris', 'İstanbul'];
  int _selectedIndex = 0;

  void _onItemTapped(int index) {
    setState(() {
      _selectedIndex = index;
    });
  }

  void initState() {
    super.initState();
    Getweather1();
  }

  chalo() {
    print(templist);
    print(weatherlist);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: const Color.fromARGB(255, 90, 86, 90),
      appBar: AppBar(
        backgroundColor: Colors.transparent,
        elevation: 0,
        leading: IconButton(
          onPressed: () {},
          icon: const Icon(
            Icons.menu,
            size: 30,
          ),
        ),
        actions: [
          IconButton(
            onPressed: () {},
            icon: const Icon(
              Icons.person_outline,
              size: 30,
            ),
          )
        ],
      ),
      body: _isLoading
          ? const Center(
              child: CircularProgressIndicator(),
            )
          : Column(
              crossAxisAlignment: CrossAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              // ignore: prefer_const_literals_to_create_immutables
              children: [
                const SizedBox(height: 16),
                Center(
                  child: const Text(
                    'City Weather',
                    style: TextStyle(
                      fontFamily: 'GabrielaStencil',
                      color: Colors.white,
                      fontSize: 28,
                      fontWeight: FontWeight.w300,
                    ),
                  ),
                ),
                const SizedBox(height: 24),
                Extendpage(
                  foregroundImages: foregroundImages,
                  backgroundImages: backgroundImages,
                  texts: texts,
                  templist: templist,
                  weatherlist: weatherlist,
                ),
              ],
            ),
      bottomNavigationBar: BottomNavigationBar(
        items: const <BottomNavigationBarItem>[
          BottomNavigationBarItem(icon: Icon(Icons.home), label: 'home'),
          BottomNavigationBarItem(icon: Icon(Icons.refresh), label: 'refresh'),
          BottomNavigationBarItem(
              icon: Icon(Icons.favorite_border), label: 'Favorite'),
        ],
        iconSize: 28,
        elevation: 0,
        backgroundColor: const Color.fromARGB(255, 90, 86, 90),
        selectedItemColor: Colors.white,
        unselectedItemColor: Colors.white54,
        showSelectedLabels: false,
        showUnselectedLabels: false,
      ),
    );
  }
}

Enter fullscreen mode Exit fullscreen mode

ExtendPage.dart

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:carousel_slider/carousel_slider.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:sensors_plus/sensors_plus.dart';

class Extendpage extends StatefulWidget {
  const Extendpage({
    Key? key,
    required this.foregroundImages,
    required this.backgroundImages,
    required this.texts,
    required this.templist,
    required this.weatherlist,
  }) : super(key: key);
  final List<String> foregroundImages;
  final List<String> backgroundImages;
  final List<String> texts;
  final List<String> templist;
  final List<String> weatherlist;
  @override
  State<Extendpage> createState() => _ExtendpageState();
}

class _ExtendpageState extends State<Extendpage> {
  double? _accelerometerXAxis;
  late final StreamSubscription<dynamic> _streamSubscription;

  late final List<String> _foregroundImages;
  late final List<String> _backgroundImages;
  late final List<String> _texts;
  late final List<String> _templist;
  late final List<String> _weatherlist;
  @override
  void initState() {
    super.initState();
    blablaFnc();
  }

  blablaFnc() {
    _foregroundImages = widget.foregroundImages;
    _backgroundImages = widget.backgroundImages;
    _texts = widget.texts;
    _templist = widget.templist;
    _weatherlist = widget.weatherlist;
    _streamSubscription = accelerometerEvents.listen(
      (AccelerometerEvent event) {
        setState(() {
          _accelerometerXAxis = event.x;
        });
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    return CarouselSlider(
      options: CarouselOptions(
        height: 520.0,
        viewportFraction: 0.80,
        enableInfiniteScroll: true,
      ),
      items: _foregroundImages.asMap().entries.map((entry) {
        int index = entry.key;
        String foregroundImage = entry.value;

        return Builder(
          builder: (BuildContext context) {
            return Padding(
              padding: const EdgeInsets.symmetric(horizontal: 10.0),
              child: ClipRRect(
                borderRadius: BorderRadius.circular(10),
                child: Stack(
                  fit: StackFit.expand,
                  children: [
                    AnimatedPositioned(
                      duration: const Duration(milliseconds: 100),
                      right: _accelerometerXAxis != null
                          ? (-350 + _accelerometerXAxis! * 30)
                          : -350,
                      child: Image.asset(
                        '${_backgroundImages[index]}',
                        fit: BoxFit.fitHeight,
                      ),
                    ),
                    AnimatedPositioned(
                      duration: const Duration(milliseconds: 100),
                      width: 320,
                      height: 500,
                      bottom: -60,
                      right: _accelerometerXAxis != null
                          ? (-13 + _accelerometerXAxis! * 1.5)
                          : -13,
                      child: Image.asset(
                        '$foregroundImage',
                        fit: BoxFit.fill,
                      ),
                    ),
                    Column(
                      children: [
                        const SizedBox(height: 20),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Icon(Icons.location_on,
                                color: Colors.white, size: 30),
                            SizedBox(
                              width: 20,
                            ),
                            Text(
                              _texts[index],
                              style: const TextStyle(
                                fontFamily: 'GabrielaStencil',
                                color: Colors.white,
                                fontSize: 30,
                                fontWeight: FontWeight.w600,
                                letterSpacing: 1,
                              ),
                            ),
                          ],
                        ),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.center,
                          children: [
                            Stack(
                              children: [
                                Container(
                                  height: 60,
                                  width: 100,
                                  color: Colors.transparent,
                                  child: Center(
                                    child: Text(
                                      _templist[index],
                                      style: GoogleFonts.bebasNeue(
                                          color: Colors.white,
                                          fontSize: 50,
                                          fontWeight: FontWeight.bold,
                                          letterSpacing: 2),
                                    ),
                                  ),
                                ),
                                Positioned(
                                  right: 15,
                                  child: Text(
                                    '0',
                                    style: GoogleFonts.bebasNeue(
                                        color: Colors.white,
                                        fontSize: 20,
                                        fontWeight: FontWeight.bold,
                                        letterSpacing: 2),
                                  ),
                                )
                              ],
                            ),
                          ],
                        ),
                        Text(
                          _weatherlist[index],
                          style: TextStyle(
                            fontFamily: 'Roboto',
                            color: Colors.white,
                            backgroundColor:
                                const Color.fromARGB(255, 90, 86, 90),
                            fontSize: 16,
                            fontWeight: FontWeight.w300,
                            letterSpacing: 1,
                          ),
                        ),
                      ],
                    )
                  ],
                ),
              ),
            );
          },
        );
      }).toList(),
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

`

Top comments (0)