repo_id
stringlengths
21
168
file_path
stringlengths
36
210
content
stringlengths
1
9.98M
__index_level_0__
int64
0
0
mirrored_repositories/RideFlutter/driver-app/lib
mirrored_repositories/RideFlutter/driver-app/lib/wallet/add_credit_sheet_view.dart
import 'package:flutter/material.dart'; import 'package:graphql_flutter/graphql_flutter.dart'; import 'package:client_shared/components/sheet_title_view.dart'; import 'package:flutter_gen/gen_l10n/messages.dart'; import 'package:ridy/graphql/generated/graphql_api.graphql.dart'; import 'package:ridy/query_result_view.dart'; import 'package:velocity_x/velocity_x.dart'; import 'package:client_shared/wallet/payment_method_item.dart'; import 'package:client_shared/wallet/money_presets_group.dart'; import 'package:url_launcher/url_launcher.dart'; import '../config.dart'; class AddCreditSheetView extends StatefulWidget { final String currency; const AddCreditSheetView({required this.currency, Key? key}) : super(key: key); @override State<AddCreditSheetView> createState() => _AddCreditSheetViewState(); } class _AddCreditSheetViewState extends State<AddCreditSheetView> { String? selectedGatewayId; double? amount; @override Widget build(BuildContext context) { return SafeArea( minimum: EdgeInsets.only( top: 16, left: 16, right: 16, bottom: MediaQuery.of(context).viewInsets.bottom + 16), child: Column( crossAxisAlignment: CrossAxisAlignment.start, mainAxisSize: MainAxisSize.min, children: [ SheetTitleView(title: S.of(context).add_credit_dialog_title), Text( S.of(context).add_credit_dialog_select_payment_method, style: Theme.of(context).textTheme.headlineMedium, ).pOnly(bottom: 8), Query( options: QueryOptions(document: PAYMENT_GATEWAYS_QUERY_DOCUMENT), builder: (QueryResult result, {Future<QueryResult?> Function()? refetch, FetchMore? fetchMore}) { if (result.isLoading || result.hasException) { return QueryResultView(result); } final gateways = PaymentGateways$Query.fromJson(result.data!) .paymentGateways; return Column( children: gateways .map((gateway) => PaymentMethodItem( id: gateway.id, title: gateway.title, selectedValue: selectedGatewayId, imageAddress: gateway.media != null ? serverUrl + gateway.media!.address : null, onSelected: (value) { setState(() => selectedGatewayId = gateway.id); })) .toList()); }), const SizedBox(height: 16), Text( S.of(context).add_credit_dialog_chose_amount, style: Theme.of(context).textTheme.headlineMedium, ), const SizedBox(height: 16), MoneyPresetsGroup( onAmountChanged: (value) => setState(() => amount = value)), const SizedBox(height: 16), SizedBox( width: double.infinity, child: Mutation( options: MutationOptions( document: TOP_UP_WALLET_MUTATION_DOCUMENT, fetchPolicy: FetchPolicy.noCache), builder: (RunMutation runMutation, QueryResult? result) { return ElevatedButton( onPressed: ((result?.isLoading ?? false) || amount == null || selectedGatewayId == null) ? null : () async { Navigator.pop(context); final mutationResult = await runMutation( TopUpWalletArguments( input: TopUpWalletInput( gatewayId: selectedGatewayId!, amount: amount!, currency: widget.currency)) .toJson()) .networkResult; final resultParsed = TopUpWallet$Mutation.fromJson( mutationResult!.data!); launchUrl(Uri.parse(resultParsed.topUpWallet.url), mode: LaunchMode.externalApplication); }, child: Text(S.of(context).top_up_sheet_pay_button), ); }), ) ], ), ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/Login.dart
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_signin_button/button_list.dart'; import 'package:flutter_signin_button/button_view.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:kisan_sahay/reset.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'HomePage.dart'; import 'package:kisan_sahay/pages/verify.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Login extends StatefulWidget { const Login({Key? key}) : super(key: key); @override _LoginState createState() => _LoginState(); } class _LoginState extends State<Login> { bool loginfail =false; final FirebaseAuth _auth = FirebaseAuth.instance; final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); String _email = ''; String _password = ''; bool _obscureText = true; bool _isLoggedIn=false; String terror='email or password doesnt match'; String temail='email'; String tpass='password'; String tsubmit='submit'; // final prefs = await SharedPreferences.getInstance(); @override void initState() { temail.translate(to: globals.lang).then((value){setState(() {temail=value.text;});}); tpass.translate(to: globals.lang).then((value){setState(() {tpass=value.text;});}); terror.translate(to: globals.lang).then((value){setState(() {terror=value.text;});}); tsubmit.translate(to: globals.lang).then((value){setState(() {tsubmit=value.text;});}); // sreg.translate(to: 'te'); // sphnone.translate(to: 'te'); super.initState(); // This will print "initState() ---> MainPage" } Future<void> signIn() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool('isLoggedin', false); // Trigger the authentication flow try { await _auth.signInWithEmailAndPassword( email: _email, password: _password); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => HomePage()), (Route<dynamic> route) => false); setState(() { loginfail = false; prefs.setBool('isLoggedin', true); print(prefs.getBool('isLoggedin')); }); } catch(e){ print(e); setState(() { print("!@#**************************************"); loginfail = true; prefs.setBool('isLoggedin', false); print(prefs.getBool('isLoggedin')); }); } } void _toggle() { setState(() { _obscureText = !_obscureText; }); } checkAuthentication() async { _auth.authStateChanges().listen((User? user) async { if (user == null) { print('User is currently signed out!'); } else { print('User is signed in!'); Navigator.push( context, MaterialPageRoute(builder: (context) => HomePage()), ); } }); @override void initState() { super.initState(); this.checkAuthentication(); // check_if_already_login(); } } @override Widget build(BuildContext context) { final translator = GoogleTranslator(); return Scaffold( appBar: AppBar( title:Text("Login To Kisan Sahay"), ), resizeToAvoidBottomInset: true, body: Container( margin: EdgeInsets.symmetric(horizontal: 35), child: SingleChildScrollView( child: Column( children: [ SizedBox(height: 20.0), Container( height: 300.0, child: Image(image: AssetImage("assets/images/login.jpg"), fit: BoxFit.contain,), ), Container( child: Form( key: _formKey, child: Column( children: [ Container( child: TextFormField( decoration: InputDecoration( labelText: temail, prefixIcon: Icon(Icons.email) ), validator: (value) { if (value!.trim().isEmpty) { return 'Please enter your email address'; } // Check if the entered email has the right format if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) { return 'Please enter a valid email address'; } // Return null if the entered email is valid return null; }, onChanged: (value) => _email = value, ), ), Container( child: new TextFormField( // controller: _passwordController, obscureText: _obscureText, decoration: InputDecoration( labelText: tpass, errorText: loginfail ? terror : null, prefixIcon: Icon(Icons.lock_rounded), suffixIcon: InkWell( onTap:_toggle , child: Icon( _obscureText ? FontAwesomeIcons.eye : FontAwesomeIcons.eyeSlash, size: 15.0, color: Colors.black, ), ) /*IconButton( icon: Icon(Icons.remove_red_eye_rounded, color: this._obscureText ? Colors.blue : Colors.grey, ), onPressed: () { setState(() => _obscureText= !_obscureText ); }, )*/ ), validator: (val) => val!.length < 6 || val == null ? 'Password too short.' : null, onChanged: (val) => _password = val, //obscureText: _obscureText, ), ), SizedBox(height: 20.0), GestureDetector( onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Reset()) ); }, child: Text( "Forgot Password ?", style: TextStyle( color: Colors.blue, fontSize: 16, decoration: TextDecoration.underline), ), ), SizedBox(height: 20.0), ElevatedButton( onPressed:() { signIn(); }, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text(tsubmit, style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white ),)) ], ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/reset.dart
import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter_signin_button/button_list.dart'; import 'package:flutter_signin_button/button_view.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'HomePage.dart'; import 'package:kisan_sahay/pages/verify.dart'; import 'package:google_sign_in/google_sign_in.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Reset extends StatefulWidget { const Reset({Key? key}) : super(key: key); @override _ResetState createState() => _ResetState(); } class _ResetState extends State<Reset> { bool loginfail =false; final FirebaseAuth _auth = FirebaseAuth.instance; final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); String _email = ''; String _password = ''; bool _obscureText = true; bool _isLoggedIn=false; String terror='email or password doesnt match'; String temail='email'; String tpass='password'; String tsubmit='submit'; // final prefs = await SharedPreferences.getInstance(); @override void initState() { temail.translate(to: globals.lang).then((value){setState(() {temail=value.text;});}); terror.translate(to: globals.lang).then((value){setState(() {terror=value.text;});}); super.initState(); // This will print "initState() ---> MainPage" } @override Widget build(BuildContext context) { final translator = GoogleTranslator(); return Scaffold( appBar: AppBar( title:Text("Reset Password"), ), resizeToAvoidBottomInset: true, body: Container( margin: EdgeInsets.symmetric(horizontal: 35), child: SingleChildScrollView( child: Column( children: [ SizedBox(height: 20.0), Container( height: 300.0, child: Image(image: AssetImage("assets/images/login.jpg"), fit: BoxFit.contain,), ), Container( child: Form( key: _formKey, child: Column( children: [ Container( child: TextFormField( decoration: InputDecoration( labelText: temail, prefixIcon: Icon(Icons.email) ), validator: (value) { if (value!.trim().isEmpty) { return 'Please enter your email address'; } // Check if the entered email has the right format if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) { return 'Please enter a valid email address'; } // Return null if the entered email is valid return null; }, onChanged: (value) => _email = value, ), ), SizedBox(height: 20.0), ElevatedButton( onPressed:() { _auth.sendPasswordResetEmail(email: _email); Navigator.of(context).pop(); }, style: ElevatedButton.styleFrom(primary: Colors .lightBlue[500], shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text("Send Request", style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white ),)) ], ), ), ), ], ), ), ), ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/globals.dart
library globals; String lang = "te";
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/HomePage.dart
import 'package:flutter/material.dart'; import 'package:kisan_sahay/Start.dart'; import 'package:kisan_sahay/pages/cart.dart'; import 'package:kisan_sahay/pages/categorylistpage.dart'; import 'package:kisan_sahay/pages/Personal.dart'; import 'package:kisan_sahay/pages/Predonate.dart'; import 'package:kisan_sahay/pages/map.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; import 'pages/yourUploads.dart'; import 'package:google_fonts/google_fonts.dart'; class HomePage extends StatefulWidget { // final String url; const HomePage({Key? key,}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State<HomePage> { User? user =FirebaseAuth.instance.currentUser; bool signedout=false; FirebaseAuth _auth=FirebaseAuth.instance; Future<Null> _signOut() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool('isLoggedin', false); await _auth.signOut(); this.setState(() { signedout = true; }); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => Start()), (Route<dynamic> route) => false); } @override Widget build(BuildContext context) { user!.reload(); return MaterialApp( home: Scaffold( resizeToAvoidBottomInset: true, backgroundColor: Colors.white, drawer: Drawer( child: ListView( children: [ UserAccountsDrawerHeader(accountName: new Text(user!.displayName.toString()), accountEmail: new Text(user!.email.toString()), currentAccountPicture: GestureDetector( onTap: () async { await Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new PersonalPage( url:user!.photoURL.toString(), )) ); setState(() { user=FirebaseAuth.instance.currentUser; print("!!!"); }); }, child: CircleAvatar( radius: 35, foregroundImage: NetworkImage(user!.photoURL.toString()), backgroundImage: AssetImage('assets/images/load1.png'), ), ) ), new ListTile( title: (globals.lang=="en") ? Text("Nearby Users") : FutureBuilder( future: "nearby users".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Nearby Users"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new NearbyMap()) ); }, ), new ListTile( title: (globals.lang=="en") ? Text("Donate Machinery") : FutureBuilder( future: "Give Machinery".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Nearby Users"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Disp()) ); }, ), new ListTile( title: (globals.lang=="en") ? Text("Need Machinery") : FutureBuilder( future: "Need machinery".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Need Machinery"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new CategoryListPage()) ); }, ), new ListTile( title: (globals.lang=="en") ? Text("Cart") : FutureBuilder( future: "Cart".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Cart"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Cart()) ); }, ), /*new ListTile( title: (globals.lang=="en") ? Text("Rented Items") : FutureBuilder( future: "Rented Items".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Rented Items"); }), onTap: () {}, ),*/ new ListTile( title: (globals.lang=="en") ? Text("Your Uploads") : FutureBuilder( future: "Your Uploads".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Your Uploads"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new YourUploads()) ); }, ), new ListTile( title: (globals.lang=="en") ? Text("Sign Out") : FutureBuilder( future: "Sign Out".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Sign Out"); }), onTap: () { //_signOut(); _signOut(); }, ), ], ), ), appBar: AppBar( title: Text('Kisan Sahay', textAlign: TextAlign.center, style: TextStyle( color: Colors.green[600], fontSize: 24.0, ),), backgroundColor: Colors.white, elevation: 0.0, /* Text('Kisan Sahay', textAlign: TextAlign.left, style: TextStyle( color: Colors.white, fontSize: 20.0, ),),*/ /* backgroundColor: Colors.lightBlueAccent, elevation: 1.0,*/ iconTheme: IconThemeData(color:Colors.green[700], ), actions: [ Container( margin: EdgeInsets.only(right: 10), padding: EdgeInsets.all(10), child: ClipOval( child: IconButton ( icon: Icon(Icons.shopping_cart), onPressed: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Cart()) ); },), ), ), Container( margin: EdgeInsets.only(right: 10), padding: EdgeInsets.fromLTRB(0,0,0,0), child: ClipOval( child: IconButton( icon: Icon(Icons.translate_rounded, color: Colors.green[600]), onPressed: () { setState(() { if(globals.lang=="te") globals.lang="en"; else globals.lang="te"; print(globals.lang); // changelang(); }); }, ), ), ) ], ), body: Container( child: Stack( children:[ Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: 20,), /* Text( "Hello! Welcome ", style: TextStyle( color: Colors.green[900], fontSize: 30, fontWeight: FontWeight.bold, ), ), */ SizedBox(height: 20.0), Center( child: Image( image: AssetImage('assets/images/welcome.jpg'), ), ), SizedBox(height: 20.0), FutureBuilder( future: "Choose Your action".translate(to: globals.lang).then((value) => value.text), initialData: "Choose your Action", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.pink, fontSize: 20, fontWeight: FontWeight.bold, ),); }), SizedBox(height: 20), Column( mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ MaterialButton( padding: EdgeInsets.symmetric( horizontal: 20, vertical: 10), color: Colors.amber , textColor: Colors.white, minWidth: 250, hoverElevation: 10, // child: FutureBuilder( future: "Share your Machinery with others".translate(to: globals.lang).then((value) => value.text), initialData: "Donate Machinery", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style:TextStyle(fontSize: 20)); }), onPressed: () {Navigator.push( context, MaterialPageRoute(builder: (context) => Disp()), );}, ), SizedBox(height: 10), MaterialButton( padding: EdgeInsets.symmetric( horizontal: 20, vertical: 10), color: Colors.amber , minWidth: 250, textColor: Colors.white, hoverElevation: 10, // child: FutureBuilder( future: "Want to Rent Machinery?".translate(to: globals.lang).then((value) => value.text), initialData: "Need Machinery?", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style:TextStyle(fontSize: 20)); }), onPressed: () {Navigator.push( context, MaterialPageRoute(builder: (context) => CategoryListPage()), );}, ), ], ) ], ), ] ), //Add bottom nav bar her //... ), ), ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/main.dart
import 'package:flutter/material.dart'; import 'package:firebase_core/firebase_core.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'l10n/L10n.dart'; import 'Start.dart'; import 'package:shared_preferences/shared_preferences.dart'; //import 'package:flutter_gen/gen_l10n/app_localizations.dart'; void main() async { WidgetsFlutterBinding.ensureInitialized(); await Firebase.initializeApp(); SharedPreferences prefs = await SharedPreferences.getInstance(); var islogin=prefs.getBool('isLoggedin'); print(islogin); runApp(MaterialApp(home: islogin==true ?HomePage() : MyApp())); } class MyApp extends StatelessWidget { static final String title ='Localization'; @override Widget build(BuildContext context) { // var data = EasyLocalizationProvider.of(context).data; return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData( primaryColor: Colors.lightBlueAccent ), /*supportedLocales: L10n.all, localizationsDelegates: [ AppLocalizations.delegate, GlobalMaterialLocalizations.delegate, GlobalCupertinoLocalizations.delegate, GlobalWidgetsLocalizations.delegate ],*/ home: Start(), //home: , //home: SelectedCategoryPage(selectedCategory: Utils.getMockedCategories()[0],), /*home: DetailsPage( subCategory: Utils.getMockedCategories()[0].subCategories[0], ),*/ ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/Start.dart
import 'package:translator/translator.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/SignUp.dart'; import 'package:kisan_sahay/phoneAuth/EnterNo.dart'; import 'package:kisan_sahay/globals.dart' as globals; import 'Login.dart'; class Start extends StatefulWidget { const Start({Key? key}) : super(key: key); @override _StartState createState() => _StartState(); } class _StartState extends State<Start> { final translator = GoogleTranslator(); @override final FirebaseAuth _auth = FirebaseAuth.instance; Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, //resizeToAvoidRightInset:true, body: Container( child: Center( child: Column( // mainAxisAlignment: MainAxisAlignment.spaceAround, //crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox(height: 45.0,), Flexible( child: Container( height: 320.0, child: Image(image:AssetImage('assets/images/Start.jfif'), fit: BoxFit.contain, ), ), ), SizedBox(height: 30.0,), Container( child: RichText( text: TextSpan( text: 'Welcome to',style:TextStyle(fontSize:25.0,fontWeight: FontWeight.bold, color: Colors.black ), children: <TextSpan>[ TextSpan( text: ' Kisan Sahay',style: TextStyle( fontSize: 30.0, fontWeight: FontWeight.bold, color: Colors.green ) ) ] ) ), ), SizedBox(height: 25.0,), Text('A New Way of Sharing instruments',style: TextStyle( color: Colors.black ), ), // SizedBox(height: 25.0,), Flexible( child: Column( //crossAxisAlignment: CrossAxisAlignment., mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ Padding( padding: EdgeInsets.only(left: 20.0,right: 20.0), child: ElevatedButton( onPressed: () {Navigator.push( context, MaterialPageRoute(builder: (context) => Login()), );}, style: ElevatedButton.styleFrom(primary: Colors.green,shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: "Sign In".translate(to: globals.lang).then((value) => value.text), initialData: "Login", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style:TextStyle( fontSize: 20.0,fontWeight: FontWeight.bold,color: Colors.white ),); }), ), ), Padding( padding: EdgeInsets.only(left: 10.0,right: 10.0), child: ElevatedButton( onPressed: () {Navigator.push( context, MaterialPageRoute(builder: (context) => SignUp()), );}, style: ElevatedButton.styleFrom(primary: Colors.green,shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: "Register".translate(to: globals.lang).then((value) => value.text), initialData: "Sign up", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style:TextStyle( fontSize: 20.0,fontWeight: FontWeight.bold,color: Colors.white ),); }), ), ) ] , ), ), /*Text("OR",style:TextStyle(fontSize: 26,fontWeight: FontWeight.bold)), ElevatedButton.icon( icon: FutureBuilder( future: "Sign-In With Phone Number".translate(to: globals.lang).then((value) => value.text), initialData: "Sign-In With Phone Number", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString()); }), label: Icon(Icons.phone), onPressed: () {Navigator.push( context, MaterialPageRoute(builder: (context) => PhoneLogin()), );}, )*/ ], ), ), ), ); } }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/lib/SignUp.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:font_awesome_flutter/font_awesome_flutter.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'package:kisan_sahay/Login.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:geolocator/geolocator.dart'; import 'Login.dart'; import 'package:geocoder/geocoder.dart'; class SignUp extends StatefulWidget { const SignUp({Key? key}) : super(key: key); @override _SignUpState createState() => _SignUpState(); } class _SignUpState extends State<SignUp> { // Define a key to access the form final _formKey = GlobalKey<FormState>(); final FirebaseAuth _auth = FirebaseAuth.instance; bool _obscureText = true; String _userEmail = ''; String _userName = ''; String _password = ''; double _latitide =1; double _longitude =1; String _confirmPassword = ''; String _phoneNo = ''; Future<double> get_locatio() async{ Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.best); _latitide= position.latitude; return position.longitude; } void _toggle() { setState(() { _obscureText = !_obscureText; }); } // This function is triggered when the user press the "Sign Up" button void _trySubmitForm() async { final isValid = _formKey.currentState!.validate(); if (isValid) { print('Everything looks good!'); print(_userEmail); print(_userName); print(_password); print(_confirmPassword); _longitude= await get_locatio(); print(_longitude); print(_latitide); UserCredential user= await _auth.createUserWithEmailAndPassword(email: _userEmail,password: _password); CollectionReference users = FirebaseFirestore.instance.collection('Users'); _auth.currentUser!.updateDisplayName(_userName); _auth.currentUser!.updatePhotoURL("https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ_mCyTdVerlZkBa4mPc5wDWUXmbGcIuxaN-1FJ1kJ8BS6rq7vrD1B4Rm33wgyRRTFccwQ&usqp=CAU"); final coordinates = new Coordinates(_latitide, _longitude); var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates); var first = addresses.first; print("${first.featureName} : ${first.addressLine}"); print("!!!!!!!!!!!!!!!"); // print(first.locality); //print("subAdminArea"+first.subAdminArea); // print(first.adminArea); // print(first.postalCode); await users.doc(_auth.currentUser!.uid).set({ 'name':_userName, 'email': _auth.currentUser!.email.toString(), 'latitude':_latitide, 'longitude':_longitude, 'phoneNumber': _phoneNo, 'rating': 1, 'locality':first.locality, 'postal':first.postalCode, 'adress':first.addressLine, }); // print(users.id.) try { await _auth.currentUser!.sendEmailVerification(); } catch (e) { print("An error occurred while trying to send email verification"); print(e); } _auth.signOut(); Navigator.push( context, MaterialPageRoute(builder: (context) => Login()), ); } } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title:Text("Sign Up "), ), resizeToAvoidBottomInset: true, body: SingleChildScrollView( child: Padding( padding: const EdgeInsets.only(top: 30.0), child: Container( color:Color(0xfff6fef6), alignment: Alignment.center, child: Container( margin: EdgeInsets.symmetric(horizontal: 35), child: Padding( padding: const EdgeInsets.only(left: 10.0,right: 20.0), child: Form( key: _formKey, child: Column( mainAxisSize: MainAxisSize.min, children: [ Container( child:Text('Register Now ',style: TextStyle(fontSize: 27.0,color: Colors.green[800]),) ), SizedBox(height: 20.0), // Email TextFormField( decoration: InputDecoration(labelText: 'Email',prefixIcon: Icon(Icons.email)), validator: (value) { if (value!.trim().isEmpty) { return 'Please enter your email address'; } // Check if the entered email has the right format if (!RegExp(r'\S+@\S+\.\S+').hasMatch(value)) { return 'Please enter a valid email address'; } // Return null if the entered email is valid return null; }, onChanged: (value) => _userEmail = value, ), /// username TextFormField( decoration: InputDecoration(labelText: 'Username',prefixIcon: Icon(Icons.supervised_user_circle_outlined)), validator: (value) { if (value!.trim().isEmpty) { return 'This field is required'; } if (value.trim().length < 4) { return 'Username must be at least 4 characters in length'; } // Return null if the entered username is valid return null; }, onChanged: (value) => _userName = value, ), /// Password TextFormField( decoration: InputDecoration( labelText: 'Password', prefixIcon: Icon(Icons.lock), suffixIcon: InkWell( onTap:_toggle , child: Icon( _obscureText ? FontAwesomeIcons.eye : FontAwesomeIcons.eyeSlash, size: 15.0, color: Colors.black, ), ) ), obscureText: true, validator: (value) { if (value!.trim().isEmpty) { return 'This field is required'; } if (value.trim().length < 8) { return 'Password must be at least 8 characters in length'; } // Return null if the entered password is valid return null; }, onChanged: (value) => _password = value, ), /// Confirm Password TextFormField( decoration: InputDecoration( labelText: 'Confirm Password', prefixIcon: Icon(Icons.lock), suffixIcon: InkWell( onTap:_toggle , child: Icon( _obscureText ? FontAwesomeIcons.eye : FontAwesomeIcons.eyeSlash, size: 15.0, color: Colors.black, ), ) ), obscureText: true, validator: (value) { if(value!.isEmpty){ return 'This field is required'; } if (value != _password) { return "Passwords doesn't match"; } return null; }, onChanged: (value) => _confirmPassword = value, ), TextFormField( keyboardType: TextInputType.number, decoration: InputDecoration( labelText: 'Phone Number', prefixIcon: Icon(Icons.phone) ), validator: (value) { if(value!.isEmpty){ return 'This field is required'; } }, onChanged: (value) => _phoneNo = value, ), SizedBox(height: 18), Container( child: ElevatedButton( onPressed: _trySubmitForm, style: ElevatedButton.styleFrom( primary: Colors.green,shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text('SIGN UP',style: TextStyle( fontSize: 20.0,fontWeight: FontWeight.bold,color: Colors.white ),)), ), SizedBox(height: 20,), Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Text( "Have an account? ", style: TextStyle( fontSize: 16, ), ), GestureDetector( onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Login()) ); }, child: Text( "Login here", style: TextStyle( color: Colors.blue, fontSize: 16, decoration: TextDecoration.underline), ), ), ], ), ], ), ), ), )), ), )); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/widgets/categorybottombar.dart
import 'package:flutter/material.dart'; class CategoryBottomBar extends StatelessWidget { @override Widget build(BuildContext context) { return Container( height: 50, decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( blurRadius: 20, color: Colors.black.withOpacity(0.2), offset: Offset.zero ) ] ), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ClipOval( child: Material( child: IconButton( icon: Icon(Icons.favorite_rounded, color: Colors.green[600]), onPressed: () {}, ), ), ), ClipOval( child: Material( child: IconButton( icon: Icon(Icons.shopping_cart, color: Colors.green[600],), onPressed: () {}, ), ), ), ClipOval( child: Material( child: IconButton( icon: Icon(Icons.pin_drop, color: Colors.green[600]), onPressed: () {}, ), ), ), ClipOval( child: Material( child: IconButton( icon: Icon(Icons.settings, color: Colors.green[600]), onPressed: () {}, ), ), ), ], ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/widgets/AdvancedDrawer.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:flutter/material.dart'; import 'package:flutter_advanced_drawer/flutter_advanced_drawer.dart'; import 'package:kisan_sahay/pages/Predonate.dart'; import 'package:kisan_sahay/pages/cart.dart'; import 'package:kisan_sahay/pages/categorylistpage.dart'; import 'package:kisan_sahay/pages/selectedcategorypage.dart'; import 'package:kisan_sahay/pages/yourUploads.dart'; import 'categorycard.dart'; class NewDrawer extends StatefulWidget { const NewDrawer({Key? key}) : super(key: key); @override _NewDrawerState createState() => _NewDrawerState(); } class _NewDrawerState extends State<NewDrawer> { final Stream<QuerySnapshot> _userStream = FirebaseFirestore.instance.collection('Users').snapshots(); @override //final _advancedDrawerController = AdvancedDrawerController(); Widget build(BuildContext context) { return Container( child:Expanded( child: StreamBuilder<QuerySnapshot>( stream: _userStream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator(strokeWidth: 5,color: Colors.red,),); } return ListView.builder(itemCount : snapshot.data!.docs.length, padding: EdgeInsets.only(bottom: 60), itemBuilder: (BuildContext ctx,i){ return /* CategoryCard( url:snapshot.data!.docs.elementAt(i)['dowurl'], name: snapshot.data!.docs[i].id, onCardClick:(){ Navigator.push(context, MaterialPageRoute( builder: (context)=> SelectedCategoryPage( typename: snapshot.data!.docs[i].id.toString(),))); }, );*/ Container( child: Text(snapshot.data!.docs.elementAt(i)['latitude'].toString()), ); } ); } ) ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/widgets/titlebar.dart
import 'package:flutter/material.dart'; import 'package:kisan_sahay/pages/cart.dart'; import 'package:kisan_sahay/globals.dart' as globals; class TitleBar extends StatefulWidget implements PreferredSizeWidget{ @override _TitleBarState createState() => _TitleBarState(); @override // TODO: implement preferredSize Size get preferredSize => new Size.fromHeight(60); } class _TitleBarState extends State<TitleBar> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Kisan Sahay', textAlign: TextAlign.center, style: TextStyle( color: Colors.green[600], fontSize: 25.0, ),), backgroundColor: Colors.transparent, elevation: 0.0, iconTheme: IconThemeData(color:Colors.green[800], ), actions: [ Container( margin: EdgeInsets.only(right: 10), padding: EdgeInsets.fromLTRB(0,0,0,0), child: ClipOval( child: Material( child: IconButton( icon: Icon(Icons.shopping_cart, color: Colors.green[600]), onPressed: () {Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Cart()) );}, ), ), ), ), /*Container( margin: EdgeInsets.only(right: 6), padding: EdgeInsets.fromLTRB(0,0,0,0), child: ClipOval( child: IconButton( icon: Icon(Icons.translate_rounded, color: Colors.green[600]), onPressed: () { setState(() { if(globals.lang=="te")globals.lang="en"; else globals.lang="te"; print(globals.lang); // changelang(); }); }, ), ), )*/ ], ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/widgets/categorycard.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/models/category.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class CategoryCard extends StatelessWidget { String url; String name; Function onCardClick; CategoryCard({required this.url,required this.name,required this.onCardClick}); @override Widget build(BuildContext context) { return GestureDetector( onTap:(){ this.onCardClick(); } , child: Container( margin: EdgeInsets.all(20.0), height: 150, child: Stack( children: [ Positioned.fill( child: ClipRRect( borderRadius:BorderRadius.circular(20), child: CachedNetworkImage( imageUrl: url, placeholder: (context, url) => Center(child: CircularProgressIndicator( color: Colors.green, )), errorWidget: (context, url, error) => Icon(Icons.error), fit: BoxFit.cover, ), ) ), Positioned( bottom:0, left:0, right:0, child: Container( height: 120, decoration: BoxDecoration( borderRadius:BorderRadius.only( bottomLeft: Radius.circular(0), bottomRight: Radius.circular(0), ), gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter, colors: [ Colors.black.withOpacity(0.7), Colors.transparent, ] ) ), ), ), Positioned( bottom: 0, child: Padding( padding:EdgeInsets.all(10), child: Row( children: [ FutureBuilder( future: this.name.translate(to: globals.lang).then((value) => value.text), initialData:this.name, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),textAlign: TextAlign.center, style: TextStyle( color: Colors.white, fontSize: 25 ),); }) ], ), ), ) ], ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/details.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:kisan_sahay/pages/cart.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:url_launcher/url_launcher.dart'as UrlLauncher; //import 'package:geolocator_platform_interface/geolocator_platform_interface.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class DetailsPage extends StatefulWidget { final String id ; final String url ; final String typename ; final String cost ; final String loc ; final String phn ; final String name ; const DetailsPage({Key? key,required this.typename,required this.name,required this.phn,required this.loc,required this.id,required this.url,required this.cost}) : super(key: key); @override _DetailsPageState createState() => _DetailsPageState(id,typename,url,cost,loc,name,phn); } class _DetailsPageState extends State<DetailsPage> { final FirebaseAuth _auth = FirebaseAuth.instance; String id ; String url ; String cost ; String typename ; String loc ; String phn ; String name ; _DetailsPageState(this.id,this.typename,this.url,this.cost,this.loc,this.name,this.phn); Future addto() async{ await FirebaseFirestore.instance.collection("Users"). doc(FirebaseAuth.instance.currentUser!.uid).collection("cart").doc(id).set( {'dowpath':url,'typename':typename,'name':name,'cost':cost.toString(),'locality':loc,'phn':phn } ); Navigator.push(context, MaterialPageRoute( builder: (context) => Cart() ) ); } @override Widget build(BuildContext context) { // String url= await ; return Scaffold( appBar: TitleBar(), body:Container( alignment: Alignment.center, child: Column( children: [ ClipRRect( borderRadius: BorderRadius.all(Radius.circular(35.0)), child: Stack( children: [ Container( height: 250, child: ClipRRect( borderRadius: BorderRadius.circular(15.0), child: CachedNetworkImage( fit: BoxFit.fill, imageUrl: url, placeholder: (context, url) => CircularProgressIndicator( color: Colors.grey, ), errorWidget: (context, url, error) => Icon(Icons.error), ), ), ) , Positioned.fill( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter , colors: [ Colors.black.withOpacity(0.6), Colors.transparent ]) ), ) ) , Positioned( bottom: 0, left: 0, right:0 , child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ FutureBuilder( future: this.typename.translate(to: globals.lang).then((value) => value.text), initialData:this.name, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.white, fontSize: 20 )); }), SizedBox(height: 10,), Container( padding: EdgeInsets.all(10), decoration: BoxDecoration ( color: Colors.pink, borderRadius: BorderRadius.circular(20), ), child: FutureBuilder( future: (cost+" per day").translate(to: globals.lang).then((value) => value.text), initialData:cost+"per day", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( fontSize: 20, color: Colors.white, )); }), ) ], ) ], ), )) ], ), ), SizedBox(height: 20,), Expanded( child: Container( child:SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ FutureBuilder( future: 'Details of the Owner:'.translate(to: globals.lang).then((value) => value.text), initialData:'Details of the Owner:', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( fontSize: 23, fontWeight: FontWeight.bold, ),); }), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Name'.translate(to: globals.lang).then((value) => value.text), initialData:'Name', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: name.translate(to: globals.lang).then((value) => value.text), initialData:name, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Location'.translate(to: globals.lang).then((value) => value.text), initialData:'Location', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: loc.translate(to: globals.lang).then((value) => value.text), initialData:loc, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Contact Details'.translate(to: globals.lang).then((value) => value.text), initialData:'Contact Details', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: phn.toString().translate(to: globals.lang).then((value) => value.text), initialData:phn.toString(), builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), Padding( padding: EdgeInsets.all(20), child: ElevatedButton( onPressed:(){ UrlLauncher.launch("tel:"+phn); /* Navigator.push(context, MaterialPageRoute( builder: (context) => PayPage() ) );*/ }, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: 'Rent Now'.translate(to: globals.lang).then((value) => value.text), initialData:'Rent Now', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); }), ),), SizedBox(height: 3,), ElevatedButton( onPressed:addto, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: 'Add to Cart'.translate(to: globals.lang).then((value) => value.text), initialData:'Add to Cart', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); }),) ], ), ) )) ], ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/Donate.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:intl/intl.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Donate extends StatefulWidget { final String typename; const Donate({Key? key,required this.typename}) : super(key: key); @override _DonateState createState() => _DonateState(typename); } class _DonateState extends State<Donate> { String typename ; _DonateState(this.typename); String _imageurl=""; late File _imagefile; bool done = false; final picker = ImagePicker(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); String cost = ''; final FirebaseAuth _auth = FirebaseAuth.instance; Future pickImage() async { await Permission.photos.request(); var per = await Permission.photos.status; if(per.isGranted) { final pickedFile = await picker.getImage(source: ImageSource.gallery); var file = File(pickedFile!.path); // var fileName = basename(pickedFile!.path); setState(() { // _imageurl =dowurl.toString(); _imagefile=file; done = true; // print(_imageurl); // _imagefile=file; }); } else{ print('permision denied for photos@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2'); } } Future submit(context) async { try { DateTime now = DateTime.now(); String formattedDate = DateFormat('yyyy-MM-dd – kk:mm:ss').format(now); Reference ref = FirebaseStorage.instance .ref() .child("uploads") .child("$formattedDate.jpg"); UploadTask uploadTask = ref.putFile(_imagefile); await uploadTask.whenComplete(() async { _imageurl = await uploadTask.snapshot.ref.getDownloadURL(); }); CollectionReference users = FirebaseFirestore.instance.collection('Users'); var docsnapshot = await users.doc(_auth.currentUser!.uid).get(); var df = (docsnapshot.data() as Map<String, dynamic>); // print(df['rating']); DocumentReference d= await FirebaseFirestore.instance.collection('Equip').doc(typename).collection('items').add( {'phn':df['phoneNumber'],'name':df['name'],'adress':df['adress'],'locality':df['locality'],'postal':df['postal'],'cost':cost.toString(),'dowpath':_imageurl,'owner':_auth.currentUser!.uid.toString(),}); await users.doc(_auth.currentUser!.uid.toString()).collection("uploads").doc(d.id).set( {'dowpath':_imageurl,'typename':typename,'name':df['name'],'cost':cost.toString(),'adress':df['adress'],'locality':df['locality'],'postal':df['postal'],'phn':df['phoneNumber']}); Navigator.pop(context); } catch (error) { print(error); print("111"); } } @override Widget build(BuildContext context) { String header= "Donate the "+ typename +" you have"; return Scaffold( backgroundColor: Colors.white, appBar:TitleBar(), body: Padding( padding: EdgeInsets.fromLTRB(30.0, 20.0, 30.0, 0.0), child: SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ FutureBuilder( future: header.translate(to: globals.lang).then((value) => value.text), initialData: "Donate the "+typename+" you have", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.pink, fontSize: 20, fontWeight: FontWeight.bold, ),); }), SizedBox(height: 10,), (done != false) ? Image.file(_imagefile, width: double.infinity, height: 200, fit: BoxFit.fill,) : Image.asset('assets/images/upload.png'), SizedBox(height: 30.0,), ElevatedButton( child: FutureBuilder( future: "Choose Image".translate(to: globals.lang).then((value) => value.text), initialData:"Choose Image", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString()); }), onPressed: pickImage, ), Container( child: Form( key: _formKey, child: Column( children: [ Container( child: TextFormField( decoration: InputDecoration( labelText: "cost Per Day", prefixIcon: Icon(Icons.money) ), keyboardType: TextInputType.number, inputFormatters:[ FilteringTextInputFormatter.digitsOnly ], // Only numbers can be entered validator: (value) { if (value!.trim().isEmpty) { return 'Please enter cost per day'; } // Return null if the entered email is valid return null; }, onChanged: (value) => cost = value.toString(), ), ), SizedBox(height: 20.0), Row( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children:[ ElevatedButton( onPressed:(){ Navigator.pop(context); }, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child:FutureBuilder( future: "Cancel".translate(to: globals.lang).then((value) => value.text), initialData:"Cancel", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style :TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); })), SizedBox(width: 20,), ElevatedButton( onPressed:(){submit(context);}, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: "Submit".translate(to: globals.lang).then((value) => value.text), initialData:"Submit", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style :TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); })), ], ), ], ), ), ) ], ), ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/Payment.dart
import 'package:flutter/material.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; class PayPage extends StatefulWidget { @override _PayPageState createState() => _PayPageState(); } class _PayPageState extends State<PayPage> { Widget build(BuildContext context) { // String url= await ; return Scaffold( appBar: TitleBar(), body:Container( child: Padding( padding: EdgeInsets.only(left: 50,top:40,right: 30), child: Column( children: [ Text("Contact the Owner", style: TextStyle(fontSize: 30, color: Colors.green[900]), ), ], ), ), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/cart.dart
import 'package:flutter/material.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'package:kisan_sahay/pages/categorylistpage.dart'; import 'package:kisan_sahay/pages/showcart.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:kisan_sahay/widgets/categorycard.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'Predonate.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Cart extends StatefulWidget { const Cart({Key? key}) : super(key: key); @override _CartState createState() => _CartState(); } class _CartState extends State<Cart> { @override Widget build(BuildContext context) { return Scaffold( appBar: TitleBar(), drawer: Drawer( child: ListView( children: [ new UserAccountsDrawerHeader(accountName: new Text('User Name'), accountEmail: new Text('[email protected]'), currentAccountPicture: new CircleAvatar( backgroundImage: new NetworkImage( 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQ_mCyTdVerlZkBa4mPc5wDWUXmbGcIuxaN-1FJ1kJ8BS6rq7vrD1B4Rm33wgyRRTFccwQ&usqp=CAU' ), ), ), new ListTile( title: new Text('Home'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new HomePage()) ); }, ), new ListTile( title: new Text('Donate Machinery'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Disp()) ); }, ), new ListTile( title: new Text('Need Machinery'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new CategoryListPage()) ); }, ), new ListTile( title: new Text('Your Orders'), onTap: () {}, ), new ListTile( title: new Text('Settings'), onTap: () {}, ), new ListTile( title: new Text('Sign Out'), onTap: () {}, ), ], ), ), body :Container( child: Stack( children:[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: EdgeInsets.only(top: 10.0,bottom: 10.0), child:FutureBuilder( future: 'Your cart'.translate(to: globals.lang).then((value) => value.text), initialData:'Your cart', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24, ),); }), ), Expanded( child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('Users').doc(FirebaseAuth.instance.currentUser!.uid).collection('cart').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator(strokeWidth: 5,color: Colors.pink,),); } if(snapshot.data!.docs.length==0) { return Container( child: Column( children: [ SizedBox(height: 50,), Image.asset('assets/images/emptyCart.png',colorBlendMode: BlendMode.lighten), Text('Your Cart is Empty',style: TextStyle( fontSize: 30,fontWeight: FontWeight.bold ),), ], ) ); } return ListView.builder(itemCount : snapshot.data!.docs.length, //(itemCount==0? return Text("Cart is Empty")) padding: EdgeInsets.only(bottom: 60), itemBuilder: (BuildContext ctx,i){ return CategoryCard( url:snapshot.data!.docs.elementAt(i)['dowpath'], name: snapshot.data!.docs.elementAt(i)['typename'], onCardClick:(){ Navigator.push(context, MaterialPageRoute( builder: (context) => Showcart( typename:snapshot.data!.docs.elementAt(i)['typename'], name:snapshot.data!.docs.elementAt(i)['name'], phn:snapshot.data!.docs.elementAt(i)['phn'], loc:snapshot.data!.docs.elementAt(i)['locality'], id: snapshot.data!.docs[i].id, url: snapshot.data!.docs.elementAt(i)['dowpath'], cost: snapshot.data!.docs.elementAt(i)['cost'].toString(), ) ) ); }, ); } ); } ) ) ], ), /* Positioned( bottom: 0, left: 0, right: 0, child: CategoryBottomBar(), )*/ ] ), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/verify.dart
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:kisan_sahay/pages/Donate.dart'; import 'package:kisan_sahay/widgets/categorybottombar.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Verify extends StatefulWidget { const Verify({Key? key}) : super(key: key); @override _VerifyState createState() => _VerifyState(); } class _VerifyState extends State<Verify> { final auth=FirebaseAuth.instance.currentUser; @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( backgroundColor: Colors.white, appBar: AppBar( title: Text('Kisan Sahay', textAlign: TextAlign.left, style: TextStyle( color: Colors.white, fontSize: 25.0, ),), backgroundColor: Colors.lightBlueAccent, elevation: 1.0, iconTheme: IconThemeData(color:Colors.white, ), ), body: Padding( padding: const EdgeInsets.fromLTRB(30.0, 10.0, 5.0, 10), child: Container( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ SizedBox(height: 20,), Text( "Hello! Welcome ", style: TextStyle( color: Colors.green[900], fontSize: 30, fontWeight: FontWeight.bold, ), ), SizedBox(height: 20.0), FutureBuilder( future: "An email has been sent to your mail for verification, Please check your inbox".translate(to: globals.lang).then((value) => value.text), initialData:"An email has been sent to your mail for verification, Please check your inbox", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), style: TextStyle( color: Colors.red, fontSize: 20, ),); }), SizedBox(height: 20.0), ElevatedButton( onPressed:(){ Navigator.pop(context); }, style: ElevatedButton.styleFrom(primary: Colors .pink, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text('Login again', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white ),)) ], ), ), ), //Add bottom nav bar her //... ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/categorylistpage.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'package:kisan_sahay/pages/selectedcategorypage.dart'; import 'package:kisan_sahay/pages/yourUploads.dart'; import 'package:kisan_sahay/widgets/categorycard.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:shared_preferences/shared_preferences.dart'; import '../Start.dart'; import 'Personal.dart'; import 'Predonate.dart'; import 'cart.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; import 'map.dart'; class CategoryListPage extends StatefulWidget { @override _CategoryListPageState createState() => _CategoryListPageState(); } class _CategoryListPageState extends State<CategoryListPage> { final Stream<QuerySnapshot> _equipStream = FirebaseFirestore.instance.collection('Equip').snapshots(); bool signedout=false; FirebaseAuth _auth=FirebaseAuth.instance; Future<Null> _signOut() async { SharedPreferences prefs = await SharedPreferences.getInstance(); prefs.setBool('isLoggedin', false); await _auth.signOut(); this.setState(() { signedout = true; }); Navigator.of(context).pushAndRemoveUntil( MaterialPageRoute(builder: (context) => Start()), (Route<dynamic> route) => false); } @override Widget build(BuildContext context) { User? user =FirebaseAuth.instance.currentUser; return Scaffold( drawer: Drawer( child: ListView( children: [ new UserAccountsDrawerHeader(accountName: new Text(user!.displayName.toString()), accountEmail: new Text(user.email.toString()), currentAccountPicture: GestureDetector( onTap: (){ Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new PersonalPage( url:user.photoURL.toString(), )) ); }, child: CircleAvatar( backgroundImage: NetworkImage(FirebaseAuth.instance.currentUser!.photoURL.toString()), ),) ), new ListTile( title: new Text('Home'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new HomePage()) ); }, ), new ListTile( title: (globals.lang=="en") ? Text("Nearby Users") : FutureBuilder( future: "nearby users".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text("Nearby Users"); }), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new NearbyMap()) ); }, ), new ListTile( title: new Text('Donate Machinery'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Disp()) ); }, ), new ListTile( title: new Text('Cart'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Cart()) ); }, ), new ListTile( title: new Text('Your Uploads'), onTap: () { Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new YourUploads()) ); }, ), new ListTile( title: new Text('Sign Out'), onTap: () { _signOut(); }, ), ], ), ), appBar: AppBar( title: Text('Kisan Sahay', textAlign: TextAlign.center, style: TextStyle( color: Colors.green[600], fontSize: 24.0, ),), backgroundColor: Colors.transparent, elevation: 0.0, iconTheme: IconThemeData(color:Colors.green[800], ), actions: [ Container( margin: EdgeInsets.only(right: 10), padding: EdgeInsets.all(10), child: ClipOval( child: IconButton( icon: Icon(Icons.shopping_cart, color: Colors.green[600]), onPressed: () {Navigator.push(context, new MaterialPageRoute(builder: (BuildContext context)=> new Cart()) );}, ), ), ) ], ), body: Container( child: Stack( children:[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: EdgeInsets.only(top: 10.0,bottom: 10.0), child:FutureBuilder( future: "Select a Category".translate(to: globals.lang).then((value) => value.text), initialData:"Select a Category", builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24, )); }) ), Expanded( child: StreamBuilder<QuerySnapshot>( stream: _equipStream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator(strokeWidth: 5,color: Colors.red,),); } return ListView.builder(itemCount : snapshot.data!.docs.length, padding: EdgeInsets.only(bottom: 60), itemBuilder: (BuildContext ctx,i){ return CategoryCard( url:snapshot.data!.docs.elementAt(i)['dowurl'], name: snapshot.data!.docs[i].id, onCardClick:(){ Navigator.push(context, MaterialPageRoute( builder: (context)=> SelectedCategoryPage( typename: snapshot.data!.docs[i].id.toString(),))); }, ); } ); } ) ) ], ), ] ), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/yourUploads.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'package:kisan_sahay/pages/showcart.dart'; import 'package:kisan_sahay/pages/Changeupload.dart'; import 'package:kisan_sahay/widgets/categorycard.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'Personal.dart'; import 'Predonate.dart'; import 'cart.dart'; import 'categorylistpage.dart'; class YourUploads extends StatefulWidget { @override _YourUploadsState createState() => _YourUploadsState(); } class _YourUploadsState extends State<YourUploads> { @override User? user =FirebaseAuth.instance.currentUser; Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: TitleBar(), body: Container( child: Stack( children:[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: EdgeInsets.only(top: 10.0,bottom: 10.0), child: Text('Your Uploads', textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24, ),), ), Expanded( child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('Users').doc(FirebaseAuth.instance.currentUser!.uid).collection('uploads').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator(strokeWidth: 5,color: Colors.pink,),); } /*if(snapshot.data!.docs.length==0) { return Container( child: Column( children: [ SizedBox(height: 50,), Image.asset('assets/images/emptyCart.png',colorBlendMode: BlendMode.lighten), Text("You have no uploads",style: TextStyle( fontSize: 30,fontWeight: FontWeight.bold ),), ], ) ); } */ return ListView.builder(itemCount : snapshot.data!.docs.length, //(itemCount==0? return Text("Cart is Empty")) padding: EdgeInsets.only(bottom: 60), itemBuilder: (BuildContext ctx,i){ return CategoryCard( url:snapshot.data!.docs.elementAt(i)['dowpath'], name: snapshot.data!.docs.elementAt(i)['typename'], onCardClick:() async { await Navigator.push(context, MaterialPageRoute( builder: (context) => Changeupload( typename:snapshot.data!.docs.elementAt(i)['typename'], id: snapshot.data!.docs[i].id, url: snapshot.data!.docs.elementAt(i)['dowpath'], cost:snapshot.data!.docs.elementAt(i)['cost'], locality:snapshot.data!.docs.elementAt(i)['locality'], ) ) ); setState(() { }); }, ); } ); } ) ) ], ), /* Positioned( bottom: 0, left: 0, right: 0, child: CategoryBottomBar(), )*/ ] ), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/map.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:geoflutterfire/geoflutterfire.dart'; import 'package:google_maps_flutter/google_maps_flutter.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:kisan_sahay/pages/show_uploads.dart'; import 'package:location/location.dart'; import 'package:rxdart/rxdart.dart'; import 'dart:async'; class NearbyMap extends StatefulWidget { const NearbyMap({Key? key}) : super(key: key); @override _NearbyMapState createState() => _NearbyMapState(); } class _NearbyMapState extends State<NearbyMap> { User? user = FirebaseAuth.instance.currentUser; Set<Marker> _markers = {}; LatLng currentLatLng = LatLng(0, 0); late GoogleMapController mapController; Location location = new Location(); FirebaseFirestore firestore = FirebaseFirestore.instance; Geoflutterfire geo = Geoflutterfire(); //Stateful data BehaviorSubject<double> radius = BehaviorSubject(); late Stream<dynamic> query; late double latitude, longitude; void _onMapCreated(GoogleMapController controller) { mapController = controller; } getlatitude() async { //CollectionReference users =FirebaseFirestore.instance.collection("Users"); var docsnt = await FirebaseFirestore.instance.collection("Users").doc( FirebaseAuth.instance.currentUser!.uid).get(); var df = docsnt.data() as Map<String, dynamic>; latitude = df['latitude']; longitude = df['longitude']; print(latitude); print(longitude); } @override initState() { //getUsers(); getlatitude(); super.initState(); } //final LatLng _center = LatLng(latitude,longitude); LatLng _center = LatLng(16.7594482, 80.6393911); @override Widget build(BuildContext context) { user!.reload(); print(_markers.length); print("!@#"); return Scaffold( appBar: TitleBar(), body: Stack( children: [ GoogleMap( mapType: MapType.normal, markers: _markers, onMapCreated: _onMapCreated, initialCameraPosition: CameraPosition( target: _center, zoom: 11.5, ), compassEnabled: true, onCameraMove: (position) { // print(position); currentLatLng = LatLng(position.target.latitude, position.target.longitude); }, ), Positioned( bottom: 50, left: 70, child: ElevatedButton( onPressed: _addGeoPoint, child: Icon(Icons.pin_drop_rounded, color: Colors.white), ), ), ], ), ); } void _addMarker() { print("Add marker"); setState(() { print(currentLatLng); _markers.add( Marker(markerId: MarkerId('1'), position: currentLatLng, //position: LatLng(17.7294,83.3093), infoWindow: InfoWindow( title: 'home', snippet: 'user home', ), ) ); }); } _animateToUser() async { LocationData pos = await location.getLocation(); mapController.animateCamera(CameraUpdate.newCameraPosition( CameraPosition( target: LatLng(pos.latitude!, pos.longitude!), zoom: 17.0 ) ) ); } Future<void> _addGeoPoint() async { await FirebaseFirestore.instance.collection("Users").get() .then((QuerySnapshot querySnapshot) { print(querySnapshot.size); var j = 0; querySnapshot.docs.forEach((doc) { print(doc['latitude']); j = j + 1; _markers.add(Marker( markerId: MarkerId(j.toString()), position: LatLng(doc["latitude"], doc["longitude"]), infoWindow: InfoWindow( title: doc['name'], snippet: 'user home', ), icon: BitmapDescriptor.defaultMarkerWithHue( BitmapDescriptor.hueViolet), onTap: () { Navigator.push(context, new MaterialPageRoute( builder: (BuildContext context) => new ShowUploads( uid: doc.id, name: doc['name'],)) ); }, )); }); }); setState(() { }); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/showcart.dart
import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:url_launcher/url_launcher.dart'as UrlLauncher; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Showcart extends StatefulWidget { final String id ; final String url ; final String typename ; final String cost ; final String loc ; final String phn ; final String name ; const Showcart( {Key? key,required this.typename,required this.name,required this.id,required this.url,required this.phn,required this.loc,required this.cost} ) : super(key: key); @override _ShowcartState createState() => _ShowcartState(id,typename,url,cost,loc,phn,name); } class _ShowcartState extends State<Showcart> { String id ; String url ; String cost ; String name ; String typename ; String loc ; String phn ; _ShowcartState(this.id,this.typename,this.url,this.cost,this.loc,this.phn,this.name); Future remove() async{ await FirebaseFirestore.instance.collection("Users").doc(FirebaseAuth.instance.currentUser!.uid).collection("cart").doc(id).delete(); Navigator.pop(context); } Widget build(BuildContext context) { // String url= await ; return Scaffold( appBar: TitleBar(), body:Container( alignment: Alignment.center, child: Column( children: [ ClipRRect( borderRadius: BorderRadius.all(Radius.circular(35.0)), child: Stack( children: [ Container( height: 250, child: ClipRRect( borderRadius: BorderRadius.circular(15.0), child: CachedNetworkImage( fit: BoxFit.fill, imageUrl: url, placeholder: (context, url) => CircularProgressIndicator( color: Colors.grey, ), errorWidget: (context, url, error) => Icon(Icons.error), ), ), ) , Positioned.fill( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter , colors: [ Colors.black.withOpacity(0.6), Colors.transparent ]) ), ) ) , Positioned( bottom: 0, left: 0, right:0 , child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(typename, style: TextStyle( color: Colors.white, fontSize: 20 ) ,) , SizedBox(height: 10,), Container( padding: EdgeInsets.all(10), decoration: BoxDecoration ( color: Colors.pink, borderRadius: BorderRadius.circular(20), ), child:Text("₹ "+cost+' per day', style: TextStyle( fontSize: 20, color: Colors.white, ),) ) ], ) ], ), )) ], ), ), SizedBox(height: 20,), Expanded( child: Container( child:SingleChildScrollView( child: Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ FutureBuilder( future: 'Details of the Owner:'.translate(to: globals.lang).then((value) => value.text), initialData:'Details of the Owner:', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( fontSize: 23, fontWeight: FontWeight.bold, ),); }), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Name'.translate(to: globals.lang).then((value) => value.text), initialData:'Name', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: name.translate(to: globals.lang).then((value) => value.text), initialData:name, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Location'.translate(to: globals.lang).then((value) => value.text), initialData:'Location', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: loc.translate(to: globals.lang).then((value) => value.text), initialData:loc, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,0), child: Row( children: [ FutureBuilder( future: 'Contact Details'.translate(to: globals.lang).then((value) => value.text), initialData:'Contact Details', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), SizedBox(width: 30,), FutureBuilder( future: phn.toString().translate(to: globals.lang).then((value) => value.text), initialData:phn.toString(), builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),style: TextStyle( color: Colors.black, fontSize: 20, ),); }), ], ), ), Padding( padding: EdgeInsets.all(20), child: ElevatedButton( onPressed:(){ UrlLauncher.launch("tel:"+phn); /* Navigator.push(context, MaterialPageRoute( builder: (context) => PayPage() ) );*/ }, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: 'Rent Now'.translate(to: globals.lang).then((value) => value.text), initialData:'Rent Now', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); }), ),), SizedBox(height: 10,), ElevatedButton( onPressed:remove, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: FutureBuilder( future: 'Remove'.translate(to: globals.lang).then((value) => value.text), initialData:'Remove', builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(), style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white )); }),) ], ), ) )) ], ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/selectedcategorypage.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/models/category.dart'; import 'package:kisan_sahay/models/subcategory.dart'; import 'package:kisan_sahay/models/subcategory.dart'; import 'package:kisan_sahay/pages/details.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:geolocator/geolocator.dart'; //import 'package:geolocator_platform_interface/geolocator_platform_interface.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class SelectedCategoryPage extends StatefulWidget { String typename ; // Stream<QuerySnapshot> _equipStream; SelectedCategoryPage({required this.typename}) {} @override _SelectedCategoryPageState createState() => _SelectedCategoryPageState(typename); } class _SelectedCategoryPageState extends State<SelectedCategoryPage> { String typename; _SelectedCategoryPageState(this.typename); /*void distance() { double distanceInMeters = Geolocator.distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838); print(distanceInMeters); }*/ @override Widget build(BuildContext context) { final Stream<QuerySnapshot> _equipStream = FirebaseFirestore.instance.collection('Equip').doc(typename).collection('items').snapshots(); double distanceInMeters = Geolocator.distanceBetween(52.2165157, 6.9437819, 52.3546274, 4.8285838); print('Distance'); print(distanceInMeters); return Scaffold( appBar: TitleBar(), body: Column( children: [ Row( mainAxisAlignment: MainAxisAlignment.center, children: [ SizedBox(height: 40,), FutureBuilder( future: this.typename.translate(to: globals.lang).then((value) => value.text), initialData:this.typename, builder: (BuildContext context, AsyncSnapshot<String> text) { return Text(text.data.toString(),textAlign: TextAlign.center, style: TextStyle( color: Colors.pink,fontSize: 30 ),); }) ], ), SizedBox(height: 10,), Expanded(child: StreamBuilder<QuerySnapshot>( stream: _equipStream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator( backgroundColor: Colors.grey, strokeWidth: 6,color: Colors.blue,),); } return GridView.count(crossAxisCount: 2, children: List.generate( snapshot.data!.docs.length, (i) { return GestureDetector( onTap:(){ // // To do : Navigate to the details page Navigator.push(context, MaterialPageRoute( builder: (context) => DetailsPage( typename:typename, loc:snapshot.data!.docs.elementAt(i)['locality'], phn:snapshot.data!.docs.elementAt(i)['phn'], name:snapshot.data!.docs.elementAt(i)['name'], id: snapshot.data!.docs[i].id, url: snapshot.data!.docs.elementAt(i)['dowpath'], cost: snapshot.data!.docs.elementAt(i)['cost'].toString(), ) ) ); } , child: Container( child: Column( children: [ /* ClipRRect( borderRadius: BorderRadius.circular(15.0), child: Image.network(snapshot.data!.docs.elementAt(i)['dowpath'], fit: BoxFit.cover,width: 150,height: 120, ), ),*/ ClipRRect( borderRadius: BorderRadius.circular(15.0), child: CachedNetworkImage( height: 120, width: 150, fit: BoxFit.fill, imageUrl: snapshot.data!.docs.elementAt(i)['dowpath'], placeholder: (context, url) => CircularProgressIndicator( color: Colors.grey, ), errorWidget: (context, url, error) => Icon(Icons.error), ), ), SizedBox(height: 10,), FutureBuilder( future: snapshot.data!.docs.elementAt(i)['locality'].toString().translate(to: globals.lang).then((value) => value.text), initialData:snapshot.data!.docs.elementAt(i)['locality'].toString(), builder: (BuildContext context, AsyncSnapshot<String> text) { // print(text); return Text(text.data.toString(),style : TextStyle( color: Colors.red, fontWeight: FontWeight.bold ),); }), Text("₹"+snapshot.data!.docs.elementAt(i)['cost'].toString(), style: TextStyle( color: Colors.black, ),) ], ), ), ); },) ); })) ] ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/Personal.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter/painting.dart'; import 'package:flutter/services.dart'; import 'package:image_picker/image_picker.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'dart:io'; import 'package:permission_handler/permission_handler.dart'; class PersonalPage extends StatefulWidget { final String url; PersonalPage({Key ?key,required this.url}) : super(key: key); @override _PersonalPageState createState() => _PersonalPageState(url); } class _PersonalPageState extends State<PersonalPage> { String url; _PersonalPageState(this.url); String _imageurl=""; late File _imagefile; bool done = false; final picker = ImagePicker(); final GlobalKey<FormState> _formKey = GlobalKey<FormState>(); int cost = 0; final FirebaseAuth _auth = FirebaseAuth.instance; Future pickImage() async { await Permission.photos.request(); var per = await Permission.photos.status; if(per.isGranted) { final pickedFile = await picker.getImage(source: ImageSource.gallery); var file = File(pickedFile!.path); // var fileName = basename(pickedFile!.path); setState(() { // _imageurl =dowurl.toString(); _imagefile=file; done = true; // print(_imageurl); // _imagefile=file; }); } else{ print('permisin denied for photos@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@2'); } } Future submit(context) async { if(done==false){ Navigator.pop(context); } try { // String displayName= Reference ref = FirebaseStorage.instance .ref() .child(_auth.currentUser!.uid); UploadTask uploadTask = ref.putFile(_imagefile); await uploadTask.whenComplete(() async { _imageurl = await uploadTask.snapshot.ref.getDownloadURL(); }); await _auth.currentUser!.updatePhotoURL(_imageurl); Navigator.pop(context); } catch (error) { print(error); } } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Container( child: Column( children: [ Padding( padding: EdgeInsets.fromLTRB(30, 50, 30, 15), child: Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: <Widget>[ GestureDetector(onTap: (){ Navigator.pop(context); }, child: Container ( height: 50, width: 50 , child: Icon(Icons.arrow_back_ios_outlined, size: 24,color: Colors.black54,), decoration: BoxDecoration(border: Border.all(color: Colors.black54), borderRadius: BorderRadius.all(Radius.circular(10))),), ), Text('Edit Profile', style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),textAlign: TextAlign.center,), SizedBox(width: 25,) ], ), ), Padding( padding: const EdgeInsets.fromLTRB(0, 0,0 ,50), child: Stack( children: <Widget>[ CircleAvatar( radius: 70, child: ClipOval(child: (done == false)?Image.network(url, height: 150, width: 150, fit: BoxFit.cover,):Image.file( _imagefile,height: 150, width: 150, fit: BoxFit.cover,),), ), Positioned(bottom: 1, right: 1 , child: Container( height: 40, width: 40, child: GestureDetector( onTap: (){ pickImage(); }, child: Icon(Icons.add_a_photo, color: Colors.white,)), decoration: BoxDecoration( color: Colors.deepOrange, borderRadius: BorderRadius.all(Radius.circular(20)) ), )) ], ), ), Expanded ( child: Container( decoration: BoxDecoration( borderRadius: BorderRadius.only(topLeft: Radius.circular(30), topRight: Radius.circular(30)), gradient: LinearGradient( begin: Alignment.topRight, end: Alignment.bottomLeft, colors: [Colors.green, Color.fromRGBO(0, 41, 102, 1)] ) ), child: Column( children: <Widget>[ Padding( padding: const EdgeInsets.fromLTRB(20, 10, 20, 4), child: Container( height: 60, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(_auth.currentUser!.displayName.toString(), style: TextStyle(color: Colors.white70),), ), ), decoration: BoxDecoration( borderRadius: BorderRadius.all(Radius.circular(20)), border: Border.all(width: 1.0, color: Colors.white70) ), ), ), Padding( padding: const EdgeInsets.fromLTRB(20, 5, 20, 4), child: Container( height: 60, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(_auth.currentUser!.email.toString(), style: TextStyle(color: Colors.white70),), ), ), decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20)),border: Border.all(width: 1.0, color: Colors.white70)), ), ), Padding( padding: const EdgeInsets.fromLTRB(20, 5, 20,0), child: Container( height: 60, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.all(8.0), child: Text('Type something about yourself', style: TextStyle(color: Colors.white70),), ), ), decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20)),border: Border.all(width: 1.0, color: Colors.white70)), ), ), /*Padding( padding: const EdgeInsets.fromLTRB(20, 5, 20, 4), child: Container( height: 60, child: Align( alignment: Alignment.centerLeft, child: Padding( padding: const EdgeInsets.all(8.0), child: Text(_auth.currentUser!.phoneNumber.toString(), style: TextStyle(color: Colors.white70),), ), ), decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(20)),border: Border.all(width: 1.0, color: Colors.white70)), ), ),*/ Expanded( child: Align( alignment: Alignment.center, child: GestureDetector( onTap: (){ submit(context);}, child: Container( height: 50, width: 180, child: Align(child: Text('Save', style: TextStyle(color: Colors.white, fontSize: 30),),), decoration: BoxDecoration( color: Colors.deepOrange, borderRadius: BorderRadius.all( Radius.circular(30),) ), ), ), ), ) ], ), ) ) ], ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/show_uploads.dart
import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/HomePage.dart'; import 'package:kisan_sahay/pages/showcart.dart'; import 'package:kisan_sahay/pages/Changeupload.dart'; import 'package:kisan_sahay/widgets/categorycard.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:kisan_sahay/pages/details.dart'; import 'Personal.dart'; import 'Predonate.dart'; import 'cart.dart'; import 'categorylistpage.dart'; class ShowUploads extends StatefulWidget { final String uid; final String name; ShowUploads({required this.uid,required this.name}) {} @override _ShowUploadsState createState() => _ShowUploadsState(uid,name); } class _ShowUploadsState extends State<ShowUploads> { String uid; String name; _ShowUploadsState(this.uid,this.name); @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: TitleBar(), body: Container( child: Stack( children:[ Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Padding( padding: EdgeInsets.only(top: 10.0,bottom: 10.0), child: Text(name+' Uploads', textAlign: TextAlign.center, style: TextStyle( color: Colors.black, fontSize: 24, ),), ), Expanded( child: StreamBuilder<QuerySnapshot>( stream: FirebaseFirestore.instance.collection('Users').doc(uid).collection('uploads').snapshots(), builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator(strokeWidth: 5,color: Colors.pink,),); } /*if(snapshot.data!.docs.length==0) { return Container( child: Column( children: [ SizedBox(height: 50,), Image.asset('assets/images/emptyCart.png',colorBlendMode: BlendMode.lighten), Text("You have no uploads",style: TextStyle( fontSize: 30,fontWeight: FontWeight.bold ),), ], ) ); } */ return ListView.builder(itemCount : snapshot.data!.docs.length, //(itemCount==0? return Text("Cart is Empty")) padding: EdgeInsets.only(bottom: 60), itemBuilder: (BuildContext ctx,i){ return CategoryCard( url:snapshot.data!.docs.elementAt(i)['dowpath'], name: snapshot.data!.docs.elementAt(i)['typename'], onCardClick:() async { await Navigator.push(context, MaterialPageRoute( builder: (context) => DetailsPage( typename:snapshot.data!.docs.elementAt(i)['typename'], loc:snapshot.data!.docs.elementAt(i)['locality'], phn:snapshot.data!.docs.elementAt(i)['phn'], name:snapshot.data!.docs.elementAt(i)['name'], id: snapshot.data!.docs[i].id, url: snapshot.data!.docs.elementAt(i)['dowpath'], cost: snapshot.data!.docs.elementAt(i)['cost'].toString(), ) ) ); setState(() { }); }, ); } ); } ) ) ], ), /* Positioned( bottom: 0, left: 0, right: 0, child: CategoryBottomBar(), )*/ ] ), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/Predonate.dart
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:kisan_sahay/pages/Donate.dart'; import 'package:kisan_sahay/widgets/categorybottombar.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:translator/translator.dart'; import 'package:kisan_sahay/globals.dart' as globals; class Disp extends StatefulWidget { const Disp({Key? key}) : super(key: key); @override _DispState createState() => _DispState(); } class _DispState extends State<Disp> { final Stream<QuerySnapshot> _equipStream = FirebaseFirestore.instance.collection('Equip').snapshots(); @override Widget build(BuildContext context) { return Scaffold( appBar: TitleBar(), body: Padding( padding: const EdgeInsets.fromLTRB(20.0, 20.0, 20.0, 0.0), child:Column( children:[ FutureBuilder( future: "Select".translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString(),style: TextStyle( color: Colors.orange[800], fontSize: 24, fontWeight: FontWeight.bold, ),);} return Text( "Select the Category", style: TextStyle( color: Colors.orange[800], fontSize: 24, fontWeight: FontWeight.bold, ), ); }), SizedBox(height: 20), Expanded(child: StreamBuilder<QuerySnapshot>( stream: _equipStream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Center(child: CircularProgressIndicator( // backgroundColor: Colors.grey, strokeWidth: 6,color: Colors.blue,),); } return ListView.builder(itemCount : snapshot.data!.docs.length, itemBuilder: (context,i){ return( Card( color: Colors.green[200], margin: EdgeInsets.fromLTRB(50,10,50,11), child: Padding( padding: EdgeInsets.all(6), child: ElevatedButton( child: FutureBuilder( future: snapshot.data!.docs[i].id.translate(to: globals.lang).then((value) => value.text), builder: (BuildContext context, AsyncSnapshot<String> text) { if(text.hasData){ return Text(text.data.toString());} return Text(snapshot.data!.docs[i].id); }), style: ElevatedButton.styleFrom( primary: Colors.pink, padding: EdgeInsets.symmetric(horizontal: 30, vertical: 15), shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(10.0), ),), onPressed: (){Navigator.push( context, MaterialPageRoute(builder: (context) => Donate(typename: snapshot.data!.docs[i].id)), );}, ), ), elevation: 1.0, ) ); },); }, ), ) ] ) ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/pages/Changeupload.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:kisan_sahay/widgets/titlebar.dart'; import 'package:cloud_firestore/cloud_firestore.dart'; import 'package:firebase_auth/firebase_auth.dart'; import 'package:firebase_storage/firebase_storage.dart'; import 'package:geolocator/geolocator.dart'; import 'package:geocoder/geocoder.dart'; class Changeupload extends StatefulWidget { final String id ; final String url ; final String typename ; final String cost ; final String locality ; const Changeupload({Key? key,required this.typename,required this.id,required this.locality,required this.url,required this.cost}) : super(key: key); @override _ChangeuploadState createState() => _ChangeuploadState(id,typename,url,cost,locality); } class _ChangeuploadState extends State<Changeupload> { String id ; String url ; String cost ; String typename ; String locality ; _ChangeuploadState(this.id,this.typename,this.url,this.cost,this.locality); Future<void> chanegloc() async{ Position position = await Geolocator.getCurrentPosition(desiredAccuracy: LocationAccuracy.high); double latitide= position.latitude; double longitude = position.longitude; final coordinates = new Coordinates(latitide, longitude); var addresses = await Geocoder.local.findAddressesFromCoordinates(coordinates); setState(() { locality=addresses.first.locality; print(locality); }); } Future changecost() async{ await FirebaseFirestore.instance.collection("Users").doc(FirebaseAuth.instance.currentUser!.uid).collection("uploads").doc(id).update({ 'cost':cost,'locality':locality }); Navigator.pop(context,); } Future del() async{ await FirebaseFirestore.instance.collection("Equip").doc(typename).collection('items').doc(id).delete(); await FirebaseFirestore.instance.collection("Users").doc(FirebaseAuth.instance.currentUser!.uid).collection("uploads").doc(id).delete(); FirebaseStorage.instance.refFromURL(url).delete(); Navigator.pop(context,); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: true, appBar: TitleBar(), body:Container( alignment: Alignment.center, child: Column( children: [ ClipRRect( borderRadius: BorderRadius.all(Radius.circular(40.0)), child: Stack( children: [ Container( height: 250, decoration: BoxDecoration( image: DecorationImage( image: NetworkImage(url), fit: BoxFit.cover, ) ), ) , Positioned.fill( child: Container( decoration: BoxDecoration( gradient: LinearGradient( begin: Alignment.bottomCenter, end: Alignment.topCenter , colors: [ Colors.black.withOpacity(0.6), Colors.transparent ]) ), ) ) , Positioned( bottom: 0, left: 0, right:0 , child: Padding( padding: const EdgeInsets.all(8.0), child: Row( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.end, children: [ Column( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(typename, style: TextStyle( color: Colors.white, fontSize: 20 ) ,) , SizedBox(height: 10,), Container( padding: EdgeInsets.all(10), decoration: BoxDecoration ( color: Colors.pink, borderRadius: BorderRadius.circular(20), ), child:Text(cost+' per day', style: TextStyle( fontSize: 20, color: Colors.white, ),) ) ], ) ], ), )) ], ), ), SizedBox(height: 20,), Expanded( child: SingleChildScrollView( child: Container( child:Column( crossAxisAlignment: CrossAxisAlignment.center, children: [ Padding( padding: EdgeInsets.only(left: 15,right:10), child: Container( child: TextFormField( decoration: InputDecoration( labelText: 'Change Cost per day', prefixIcon: Icon(Icons.money) ), keyboardType: TextInputType.number, inputFormatters:[ FilteringTextInputFormatter.digitsOnly ], // Only numbers can be entered validator: (value) { if (value!.trim().isEmpty) { return 'Please enter cost per day'; } // Return null if the entered email is valid return null; }, onChanged: (value) => cost =value.toString(), ), ), ), SizedBox(height: 20,), Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Text('Other Details', style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold ), ), SizedBox(height: 20), Padding( padding: EdgeInsets.fromLTRB(20, 0,0,20), child: Row( children: [ Text( 'Location',style: TextStyle( color: Colors.black, fontSize: 20, ),), SizedBox(width: 50,), Text(locality, textAlign: TextAlign.right, style: TextStyle( color: Colors.black, fontSize: 20, ),), ], ), ), /* ElevatedButton( onPressed: (){}, //onPressed: del, style: ElevatedButton.styleFrom( primary: Colors.lightBlueAccent, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),),*/ //child: Center( child: ElevatedButton.icon( icon: Icon( Icons.location_on_sharp, color: Colors.white, size: 24.0, ), label: Text('Change Location'), onPressed: chanegloc, style: ElevatedButton.styleFrom( shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(30.0), ), ), ) ) //), ], ), Padding( padding: EdgeInsets.all(10), child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ ElevatedButton( onPressed: del, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text('Delete ', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white ),) ), //SizedBox(width: 70,), ElevatedButton( onPressed:changecost, style: ElevatedButton.styleFrom(primary: Colors .green, shape: new RoundedRectangleBorder( borderRadius: new BorderRadius.circular(20.0), ),), child: Text('Save changes', style: TextStyle( fontSize: 20.0, fontWeight: FontWeight.bold, color: Colors.white ),)) ], ), ) ], ) ), )) ], ), ), ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/models/subcategory.dart
import 'dart:ui'; import 'package:kisan_sahay/models/category.dart'; class SubCategory extends Category{ SubCategory({ required Color color, required String name, required String imgName, required subCategories }):super( color: color, name: name, imgName: imgName, subCategories: subCategories ); }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/models/category.dart
import 'package:flutter/material.dart'; import 'dart:ui'; class Category{ String name; Color color; String imgName; List<Category> subCategories; Category( {required this.color, required this.name, required this.imgName, required this.subCategories, } ) { } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/models/categorypart.dart
import 'package:flutter/material.dart'; class CategoryPart{ String name; String imgName; bool isSelected=false; CategoryPart({ required this.name, required this.imgName, required this.isSelected }){} }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/helpers/utils.dart
import 'package:kisan_sahay/models/category.dart'; import 'package:flutter/material.dart'; class Utils{ static List<Category> getMockedCategories() { return[ Category( color:Colors.black, name:"Cultivator", imgName:"cultivators", subCategories:[ Category( color:Colors.black, name:"Cultivator", imgName:"cultivator1", subCategories:[] ), Category( color:Colors.black, name:"Cultivator", imgName:"cultivator2", subCategories:[] ), Category( color:Colors.black, name:"Cultivator", imgName:"cultivator3", subCategories:[] ), Category( color:Colors.black, name:"Cultivator", imgName:"cultivator4", subCategories:[] ), Category( color:Colors.black, name:"Cultivator", imgName:"cultivator5", subCategories:[] ), Category( color:Colors.black, name:"Cultivator", imgName:"cultivator1", subCategories:[] ), ] ), Category( color:Colors.black, name:"Planters", imgName:"planters", subCategories:[] ), Category( color:Colors.black, name:"Plough", imgName:"plough", subCategories:[] ), Category( color:Colors.black, name:"Wheel Table Scrapers", imgName:"scrapers", subCategories:[] ), Category( color:Colors.black, name:"Tractors", imgName:"tractor", subCategories:[] ), Category( color:Colors.black, name:"Weeders", imgName:"weeders", subCategories:[] ), ]; } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/phoneAuth/EnterNo.dart
import 'package:firebase_auth/firebase_auth.dart'; import 'package:flutter/material.dart'; import 'package:kisan_sahay/HomePage.dart'; enum MobileVerificationState{ SHOW_MOBILE_FORM_STATE, SHOW_OTP_FORM_STATE, } class PhoneLogin extends StatefulWidget { @override _PhoneLoginState createState() => _PhoneLoginState(); } class _PhoneLoginState extends State<PhoneLogin> { MobileVerificationState currentState= MobileVerificationState.SHOW_MOBILE_FORM_STATE; final phoneController = TextEditingController(); final otpController=TextEditingController(); FirebaseAuth _auth = FirebaseAuth.instance; late String verificationId ; bool showLoading=false; void signInWithPhoneAuthCredential(PhoneAuthCredential phoneAuthCredential) async { setState(() { showLoading=true; }); try{ final authCredential = await _auth.signInWithCredential(phoneAuthCredential); setState(() { showLoading=false; }); if(authCredential.user !=null) { Navigator.push(context,MaterialPageRoute(builder: (context)=> HomePage())); } } on FirebaseAuthException catch(e){ setState(() { showLoading=false; }); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text("Some Error Occurred!"), duration: Duration(milliseconds: 300), ), ); } } late String _phoneNo; getMobileFormWidget(context) { return Padding( padding: EdgeInsets.fromLTRB(10, 0, 10, 10), child: Column( children: [ Spacer(), Text( "Login With Ph No", style: TextStyle( fontSize: 25.0 ), ), SizedBox(height: 20,), TextFormField( controller: phoneController, keyboardType: TextInputType.number, decoration: InputDecoration(labelText: 'Phone Number',prefixIcon: Icon(Icons.phone)), validator: (value) { if(value!.isEmpty){ return 'This field is required'; } }, onChanged: (value) => _phoneNo = value, ), SizedBox(height: 20,), ElevatedButton( onPressed: () async{ setState(() { showLoading=true; }); await _auth.verifyPhoneNumber( phoneNumber: "+91"+phoneController.text, verificationCompleted: (phoneAuthCredential) async { setState(() { showLoading=false; }); //signInWithPhoneAuthCredential(phoneAuthCredential); }, verificationFailed: (verificationFailed) async { //_scaffoldKey.currentState!.showSnackBar(SnackBar(content: Text(verificationFailed.message))); ScaffoldMessenger.of(context).showSnackBar( SnackBar( content: Text(verificationFailed.message!), duration: Duration(milliseconds: 300), ), ); }, codeSent: (verificationId,resendingToken) async { setState(() { showLoading=false; currentState = MobileVerificationState.SHOW_OTP_FORM_STATE; this.verificationId = verificationId; }); }, codeAutoRetrievalTimeout: (verificationId) async { } ); }, child: Text("SEND"), //color:Colors.blueGrey autofocus: true, ), Spacer(), ], ), ); } getOtpFormWidget(context) { return Padding( padding: EdgeInsets.fromLTRB(10, 0, 10, 10), child: Column( children: [ Spacer(), Text( "Enter the OTP", style: TextStyle( fontSize: 25.0 ), ), SizedBox(height: 20,), TextFormField( controller: otpController, keyboardType: TextInputType.number, decoration: InputDecoration(labelText: 'OTP',prefixIcon: Icon(Icons.lock_outline)), validator: (value) { if(value!.isEmpty){ return 'This field is required'; } }, onChanged: (value) => _phoneNo = value, ), SizedBox(height: 20,), ElevatedButton( onPressed: () async{ PhoneAuthCredential phoneAuthCredential= PhoneAuthProvider.credential( verificationId: verificationId, smsCode: otpController.text); signInWithPhoneAuthCredential(phoneAuthCredential); }, child: Text("Verify"), //color:Colors.blueGrey autofocus: true, ), Spacer(), ], ), ); } final GlobalKey<ScaffoldState> _scaffoldKey= GlobalKey(); @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, body:Container( child: showLoading?Center(child:CircularProgressIndicator()): currentState==MobileVerificationState.SHOW_MOBILE_FORM_STATE? getMobileFormWidget(context): getOtpFormWidget(context), padding: const EdgeInsets.all(16), ) ); } }
0
mirrored_repositories/kisanSahay/lib
mirrored_repositories/kisanSahay/lib/l10n/L10n.dart
import 'package:flutter/material.dart'; class L10n { static final all=[ const Locale('en'), const Locale('hi'), const Locale('te'), const Locale('ta'), ]; }
0
mirrored_repositories/kisanSahay/google_maps_in_flutter
mirrored_repositories/kisanSahay/google_maps_in_flutter/lib/main.dart
import 'package:flutter/material.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 Demo', theme: ThemeData( // This is the theme of your application. // // Try running your application with "flutter run". You'll see the // application has a blue toolbar. Then, without quitting the app, try // changing the primarySwatch below to Colors.green and then invoke // "hot reload" (press "r" in the console where you ran "flutter run", // or simply save your changes to "hot reload" in a Flutter IDE). // Notice that the counter didn't reset back to zero; the application // is not restarted. primarySwatch: Colors.blue, ), home: MyHomePage(title: 'Flutter Demo Home Page'), ); } } class MyHomePage extends StatefulWidget { MyHomePage({Key? key, required this.title}) : super(key: key); // This widget is the home page of your application. It is stateful, meaning // that it has a State object (defined below) that contains fields that affect // how it looks. // This class is the configuration for the state. It holds the values (in this // case the title) provided by the parent (in this case the App widget) and // used by the build method of the State. Fields in a Widget subclass are // always marked "final". final String title; @override _MyHomePageState createState() => _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void _incrementCounter() { setState(() { // This call to setState tells the Flutter framework that something has // changed in this State, which causes it to rerun the build method below // so that the display can reflect the updated values. If we changed // _counter without calling setState(), then the build method would not be // called again, and so nothing would appear to happen. _counter++; }); } @override Widget build(BuildContext context) { // This method is rerun every time setState is called, for instance as done // by the _incrementCounter method above. // // The Flutter framework has been optimized to make rerunning build methods // fast, so that you can just rebuild anything that needs updating rather // than having to individually change instances of widgets. return Scaffold( appBar: AppBar( // Here we take the value from the MyHomePage object that was created by // the App.build method, and use it to set our appbar title. title: Text(widget.title), ), body: Center( // Center is a layout widget. It takes a single child and positions it // in the middle of the parent. child: Column( // Column is also a layout widget. It takes a list of children and // arranges them vertically. By default, it sizes itself to fit its // children horizontally, and tries to be as tall as its parent. // // Invoke "debug painting" (press "p" in the console, choose the // "Toggle Debug Paint" action from the Flutter Inspector in Android // Studio, or the "Toggle Debug Paint" command in Visual Studio Code) // to see the wireframe for each widget. // // Column has various properties to control how it sizes itself and // how it positions its children. Here we use mainAxisAlignment to // center the children vertically; the main axis here is the vertical // axis because Columns are vertical (the cross axis would be // horizontal). mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ Text( 'You have pushed the button this many times:', ), Text( '$_counter', style: Theme.of(context).textTheme.headline4, ), ], ), ), floatingActionButton: FloatingActionButton( onPressed: _incrementCounter, tooltip: 'Increment', child: Icon(Icons.add), ), // This trailing comma makes auto-formatting nicer for build methods. ); } }
0
mirrored_repositories/kisanSahay/google_maps_in_flutter
mirrored_repositories/kisanSahay/google_maps_in_flutter/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:google_maps_in_flutter/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/kisanSahay
mirrored_repositories/kisanSahay/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:kisan_sahay/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/Flutter-Custom-DatePicker
mirrored_repositories/Flutter-Custom-DatePicker/lib/main.dart
import 'package:flutter/material.dart'; import 'ui/screens/HomeScreen.dart'; void main() => runApp(MyApp()); class MyApp extends StatelessWidget { @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, theme: ThemeData(primaryColor: Colors.amber), home: HomeScreen(), ); } }
0
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui/components/CalendarWidget.dart
import 'package:flutter/material.dart'; import 'MonthCalendarWidget.dart'; typedef void OnResultDate(DateTime dateTime); class CalendarWidget extends StatefulWidget { final totalAddMonth; final OnResultDate onResultDate; const CalendarWidget({Key key, this.totalAddMonth, this.onResultDate}) : super(key: key); @override _CalendarWidgetState createState() => _CalendarWidgetState(); } class _CalendarWidgetState extends State<CalendarWidget> { DateTime currentDate; @override void initState() { currentDate = DateTime.now(); currentDate = DateTime(currentDate.year,currentDate.month,currentDate.day); super.initState(); } @override Widget build(BuildContext context) { return ListView.builder( itemBuilder: (BuildContext context, int index) { return Container( margin: EdgeInsets.only(top: 16), child: MonthCalendarWidget( currentDate: currentDate, startDate: getDateByPosition(index), onSelect: (DateTime selectedDate) { setState(() { currentDate = selectedDate; widget.onResultDate(selectedDate); /* showDialog( context: context, builder: (BuildContext context) { return AlertDialog( title: Text("Tarih Onayı"), content: Text("Tarih: $selectedDate}"), actions: <Widget>[ RaisedButton( child: Text("Onayla"), onPressed: () => { widget.onResultDate(selectedDate), }, ) ], ); });*/ }); }, ), ); }, itemCount: getTotalMonth(widget.totalAddMonth), ); } int getTotalMonth(int addDayCount) { var addFiveMonthAtNow = DateTime.now().add(Duration(days: addDayCount * 30)); var calculatedYear = addFiveMonthAtNow.year - DateTime.now().year; var calculatedMonthCount = 12 * calculatedYear; return calculatedMonthCount + addFiveMonthAtNow.month - DateTime.now().month; } DateTime getDateByPosition(int monthIndex) { DateTime startDate = DateTime.now(); startDate = DateTime(startDate.year,startDate.month,startDate.day); if (monthIndex != 0) { startDate = startDate.add(Duration(days: ((monthIndex) * 30))); } return startDate; } }
0
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui/components/MonthCalendarWidget.dart
import 'dart:io'; import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'WeekDaysFirstRow.dart'; typedef void OnSelect(DateTime date); class MonthCalendarWidget extends StatefulWidget { final DateTime startDate; final DateTime currentDate; final OnSelect onSelect; const MonthCalendarWidget({Key key, this.startDate, this.currentDate, this.onSelect}) : super(key: key); @override _MonthCalendarWidgetState createState() => _MonthCalendarWidgetState(); } class _MonthCalendarWidgetState extends State<MonthCalendarWidget> { int rowStartDay = 0; DateTime onTapDate; DateTime currentDate; @override void initState() { onTapDate = DateTime(2000, 01, 01); currentDate = DateTime.now().subtract(Duration(days: 1)); super.initState(); } @override Widget build(BuildContext context) { return Column(children: createRows()); } List<Widget> createRows() { List<Widget> rows = []; rows.add(dateInfoWidget); rows.add(SizedBox(height: 8)); rows.add(Divider( height: 3, )); rows.add(SizedBox(height: 8)); rows.add(WeekDaysFirstRow()); rows.add(SizedBox(height: 16)); var rowStartElement = widget.startDate.subtract(Duration(days: widget.startDate.day - 1)); // ayın 1. gününü alır for (int columnPosition = 1; columnPosition < 7; columnPosition++) { // add 6 row in column rows.add(Row(children: prepareOneWeek(rowStartElement, columnPosition))); rowStartElement = rowStartElement.add(Duration(days: rowStartDay)); } return rows; } List<Widget> prepareOneWeek(DateTime rowStartDate, int columnPosition) { List<Widget> rowItems = []; rowStartDay = 0; int monthStartDay = rowStartDate.weekday; DateTime rowStartDayOnMonth = rowStartDate; DateTime nextMonth = DateTime(widget.startDate.year, widget.startDate.month + 1, 0).add(Duration(days: 1)); if (columnPosition == 1) { for (int rowPosition = 1; rowPosition < 8; rowPosition++) { // Create row element (7) if (rowPosition == monthStartDay) { // query for month first day rowItems.add(_fullDay(rowStartDayOnMonth)); rowStartDayOnMonth = rowStartDayOnMonth.add(Duration(days: 1)); rowStartDay++; } else if (rowPosition > monthStartDay) { if (nextMonth.isAfter(rowStartDayOnMonth)) { // is next Month ? rowItems.add(_fullDay(rowStartDayOnMonth)); rowStartDayOnMonth = rowStartDayOnMonth.add(Duration(days: 1)); rowStartDay++; } else { rowItems.add(_emptyDay); } } else { rowItems.add(_emptyDay); } } } else { for (int rowPosition = 1; rowPosition < 8; rowPosition++) { // Create row element (7) if (nextMonth.isAfter(rowStartDayOnMonth)) { // is next Month ? rowItems.add(_fullDay(rowStartDayOnMonth)); rowStartDayOnMonth = rowStartDayOnMonth.add(Duration(days: 1)); rowStartDay++; } else { rowItems.add(_emptyDay); } } } return rowItems; } Widget _fullDay(DateTime date) => Expanded( child: InkWell( onTap: () => { setState(() { if (date.isAfter(currentDate)) { onTapDate = date; widget.onSelect(date); } }) }, child: Container( decoration: BoxDecoration( color: date.isAfter(currentDate) ? isDateToday(date) ? Colors.pink : Colors.white : Colors.black45, borderRadius: BorderRadius.circular(8), ), margin: EdgeInsets.all(5), height: 32, width: 32, alignment: Alignment.center, child: Text( date.day.toString(), textAlign: TextAlign.center, style: TextStyle(color: date.isAfter(currentDate) ? isDateToday(date) ? Colors.white : Colors.black : Colors.white, fontWeight: FontWeight.bold), ), ), ), ); bool isDateToday(DateTime rowDateTime) { rowDateTime = DateTime(rowDateTime.year, rowDateTime.month, rowDateTime.day); DateTime currentNewDate = DateTime(widget.currentDate.year, widget.currentDate.month, widget.currentDate.day); if (rowDateTime == currentNewDate) { return true; } else { return false; } } Widget get _emptyDay => Expanded(child: Text("", textAlign: TextAlign.center, style: TextStyle(color: Colors.white))); Widget get dateInfoWidget => Center( child: Text( " ${DateFormat(DateFormat.MONTH, Platform.localeName).format(widget.startDate)} ${DateFormat(DateFormat.YEAR, Platform.localeName).format(widget.startDate)}")); }
0
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui/components/WeekDaysFirstRow.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; class WeekDaysFirstRow extends StatelessWidget { List<String> get _weekNameList { DateFormat date = DateFormat.yMMM(Platform.localeName); List<String> weekNameList = List(); for (int i = 1; i < 8; i++) { weekNameList.add(date.dateSymbols.STANDALONESHORTWEEKDAYS[i == 7 ? 0 : i]); } return weekNameList; } List<Widget> get _createWeekRowElements { List<String> nameList = List.from(_weekNameList); List<Widget> elementList = List(); for (int i = 0; i < 7; i++) { elementList.add(Expanded( child: Text( nameList[i], textAlign: TextAlign.center, style: textStyle, ), )); } return elementList; } @override Widget build(BuildContext context) { return Row( children: _createWeekRowElements, ); } TextStyle get textStyle => TextStyle(fontFamily: "playfair-regular", fontSize: 14.2, fontWeight: FontWeight.w600, letterSpacing: 1, color: Colors.black45); }
0
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui/screens/CalendarScreen.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../components/CalendarWidget.dart'; class CalendarScreen extends StatefulWidget { @override _CalendarScreenState createState() => _CalendarScreenState(); } class _CalendarScreenState extends State<CalendarScreen> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Tarih Seçin"), ), body: SafeArea( child: CalendarWidget( totalAddMonth: 15, onResultDate: (DateTime dateTime) { Navigator.of(context).pop(dateTime); }, ), ), ); } }
0
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui
mirrored_repositories/Flutter-Custom-DatePicker/lib/ui/screens/HomeScreen.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:intl/intl.dart'; import 'package:intl/date_symbol_data_local.dart'; import 'CalendarScreen.dart'; class HomeScreen extends StatefulWidget { @override _HomeScreenState createState() => _HomeScreenState(); } class _HomeScreenState extends State<HomeScreen> { final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(); @override void initState() { super.initState(); initializeDateFormatting(); } @override Widget build(BuildContext context) { return Scaffold( key: _scaffoldKey, appBar: AppBar( title: Text("Custom Calendar App"), ), body: Center( child: RaisedButton( onPressed: () => { Navigator.of(context).push(MaterialPageRoute(builder: (context) => CalendarScreen())).then( (dateTime) => { if(dateTime != null){ _showDate(dateTime) } }, ) }, color: Colors.blue, child: Text( "Takvimi Aç", style: TextStyle(color: Colors.white), ), ), ), ); } _showDate(DateTime dateTime) { var dateStandard = DateFormat("d.M.y",Platform.localeName).format(dateTime); var dateNamedMonth = DateFormat("d MMMM y",Platform.localeName).format(dateTime); var dateShortMonthDay = DateFormat("d MMM y EEEE",Platform.localeName).format(dateTime); var dateShortMonthShortDay = DateFormat("d MMM y E",Platform.localeName).format(dateTime); _scaffoldKey.currentState.showSnackBar(SnackBar( content: SingleChildScrollView( child: Column( children: <Widget>[ Text("Gelen Tarih: $dateStandard"), Text("Gelen Tarih: $dateNamedMonth"), Text("Gelen Tarih: $dateShortMonthDay"), Text("Gelen Tarih: $dateShortMonthShortDay"), ], ), ), )); } }
0
mirrored_repositories/Flutter-Custom-DatePicker
mirrored_repositories/Flutter-Custom-DatePicker/test/widget_test.dart
// This is a basic Flutter widget test. // // To perform an interaction with a widget in your test, use the WidgetTester // utility that Flutter provides. For example, you can send tap and scroll // gestures. You can also use WidgetTester to find child widgets in the widget // tree, read text, and verify that the values of widget properties are correct. import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:biletall_project2_calendar/main.dart'; void main() { testWidgets('Counter increments smoke test', (WidgetTester tester) async { // Build our app and trigger a frame. await tester.pumpWidget(MyApp()); // Verify that our counter starts at 0. expect(find.text('0'), findsOneWidget); expect(find.text('1'), findsNothing); // Tap the '+' icon and trigger a frame. await tester.tap(find.byIcon(Icons.add)); await tester.pump(); // Verify that our counter has incremented. expect(find.text('0'), findsNothing); expect(find.text('1'), findsOneWidget); }); }
0
mirrored_repositories/SimplicityWeather
mirrored_repositories/SimplicityWeather/lib/main.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/views/app/bloc_wrapper.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; void main() => runApp(BlocWrapper(child: FlutterApp()));
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/app/flutter_app.dart
import 'package:amap_location_fluttify/amap_location_fluttify.dart'; import 'package:event_bus/event_bus.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/image_utils.dart'; import 'package:flutter_dynamic_weather/views/common/loading_dialog.dart'; import 'package:flutter_dynamic_weather/views/common/ota_dialog.dart'; import 'package:flutter_dynamic_weather/views/pages/home/home_page.dart'; import 'dart:ui' as ui; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; EventBus eventBus = EventBus(); GlobalKey globalKey = GlobalKey(); ValueNotifier<double> offsetNotifier = ValueNotifier<double>(0); Map<WeatherType, ui.Image> weatherImages = {}; void showAppDialog({String loadingMsg = "正在加载中..."}) { showDialog<LoadingDialog>( context: globalKey.currentContext, barrierDismissible: false, builder: (BuildContext context) { return new LoadingDialog( text: loadingMsg, ); }); } void showOTADialog(String apkUrl, String desc, String versionName) { showDialog<LoadingDialog>( context: globalKey.currentContext, barrierDismissible: false, builder: (BuildContext context) { return new OTADialog(desc, versionName, apkUrl); }); } void fetchWeatherImages() async { WeatherType.values.forEach((element) async { weatherImages[element] = await ImageUtils.getImage(WeatherUtils.getWeatherIcon(element)); }); } class FlutterApp extends StatelessWidget { @override Widget build(BuildContext context) { fetchWeatherImages(); AmapLocation.instance.init(iosKey: "1acd2fca2d9361152f3e77d0d7807043"); return MaterialApp( title: "动态天气", debugShowCheckedModeBanner: false, onGenerateRoute: WeatherRouter.generateRoute, navigatorObservers: [AppAnalysis()], color: Colors.blue[600], home: AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.light, child: HomePage(key: globalKey), ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/app/bloc_wrapper.dart
import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/bloc/weather/weather_bloc.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; class BlocWrapper extends StatelessWidget { final Widget child; final weatherApi = WeatherApi(); BlocWrapper({@required this.child}); @override Widget build(BuildContext context) { return MultiBlocProvider( providers: [ BlocProvider<CityBloc>(create: (_) => CityBloc(weatherApi)..add(FetchCityDataEvent())), BlocProvider<WeatherBloc>(create: (_) => WeatherBloc(weatherApi)), ], child: child, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/about/about_page.dart
import 'package:flutter/gestures.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_weather_bg/bg/weather_bg.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; import 'package:package_info/package_info.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; import 'package:url_launcher/url_launcher.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class AboutPage extends StatefulWidget { @override _AboutPageState createState() => _AboutPageState(); } class _AboutPageState extends State<AboutPage> { WeatherType _weatherType = WeatherType.sunny; String _version; String _appName; Widget _buildBg(BuildContext context) { var width = MediaQuery.of(context).size.width; var height = MediaQuery.of(context).size.height; return Stack( children: [ Container( decoration: BoxDecoration( gradient: LinearGradient( colors: WeatherUtil.getColor(_weatherType), stops: [0, 1], begin: Alignment.topCenter, end: Alignment.bottomCenter, )), ), WeatherBg( weatherType: _weatherType, width: width, height: height, ) ], ); } @override void initState() { getVersion(); super.initState(); } void getVersion() { PackageInfo.fromPlatform().then((PackageInfo packageInfo) { setState(() { _version = packageInfo.version; _appName = packageInfo.appName; }); }); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Stack( children: [ _buildBg(context), BlurRectWidget( sigmaX: 0, sigmaY: 0, child: Container( padding: EdgeInsets.only( top: MediaQueryData.fromWindow( WidgetsBinding.instance.window) .padding .top), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( height: kToolbarHeight, child: Stack( children: [ Container( padding: EdgeInsets.only(left: 6), alignment: Alignment.centerLeft, child: IconButton( icon: Icon( Icons.arrow_back_ios, color: Colors.white, size: 20, ), onPressed: () { Navigator.of(context).pop(); }, ), ), Align( child: Text( "关于", style: TextStyle( fontSize: 20, color: Colors.white), ), ), Container( padding: EdgeInsets.only(right: 9), alignment: Alignment.centerRight, child: IconButton( icon: Icon( Icons.more_vert, color: Colors.white, size: 20, ), onPressed: () { Navigator.of(context) .pushNamed(WeatherRouter.example); }, ), ), ], )), Container( height: 1.sh - MediaQueryData.fromWindow( WidgetsBinding.instance.window) .padding .top - kToolbarHeight, child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( height: 200, ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, crossAxisAlignment: CrossAxisAlignment.end, children: [ Container( margin: EdgeInsets.only(left: 20), decoration: BoxDecoration( image: DecorationImage( image: AssetImage( "assets/images/ic_launcher.png"), fit: BoxFit.cover, ), border: Border.all( color: Colors.white, width: 2, ), borderRadius: BorderRadius.circular(100), ), width: 100, height: 100, ), Container( margin: EdgeInsets.only(right: 20), child: RaisedButton( color: Colors.blue, shape: RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(18.0), ), ), onPressed: () async { const url = 'https://github.com/xiaweizi/SimplicityWeather'; if (await canLaunch(url)) { UmengAnalyticsPlugin.event( AnalyticsConstant.aboutClick, label: "简悦天气-github"); await launch(url); } }, child: Text( "Github", style: TextStyle( color: Colors.white, fontSize: 16), ), ), ), ], ), Container( margin: EdgeInsets.only(left: 20, top: 20), child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text(_appName == null ? "简悦天气" : _appName, style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 30)), SizedBox( width: 20, ), Text("v$_version", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white.withAlpha(200), fontSize: 16)), ]), ), Container( margin: EdgeInsets.only(left: 20, top: 10), child: Text( "简约不简单,丰富不复杂", style: TextStyle( color: Colors.white, fontSize: 16), ), ), Container( margin: EdgeInsets.only(left: 20, top: 20), child: Text( "项目简介", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20), ), ), Container( margin: EdgeInsets.only(left: 20, top: 10), child: Text( "一款简约风格的 flutter 天气项目,提供实时、多日、24 小时、台风路径以及生活指数等服务,支持定位、删除、搜索等操作。\n\n " + "作为 flutter 实战项目,包含状态管理、网络请求、数据缓存、自定义 view、自定义动画,三方统计,事件管理等技术点,实用且丰富。", style: TextStyle( color: Colors.white, fontSize: 16), ), ), Container( margin: EdgeInsets.only(left: 20, top: 20), child: Text( "作者简介", style: TextStyle( fontWeight: FontWeight.bold, color: Colors.white, fontSize: 20), ), ), Container( margin: EdgeInsets.only(left: 20, top: 10), child: RichText( text: TextSpan( style: TextStyle( color: Colors.white, fontSize: 16), children: <InlineSpan>[ _buildPersonHome( "个人主页", "http://xiaweizi.cn/"), TextSpan(text: '\n\n'), _buildPersonHome("Github", "https://github.com/xiaweizi"), TextSpan(text: '\n\n'), _buildPersonHome("简书", "https://www.jianshu.com/u/d36586119d8c"), TextSpan(text: '\n\n'), _buildPersonHome("掘金", "https://juejin.im/user/2313028193761389"), TextSpan(text: '\n\n'), _buildPersonHome("CSDN", "https://blog.csdn.net/qq_22656383"), ]), ), ), SizedBox( height: 40, ) ], ), ), ) ], ), ), ), ], )); } TextSpan _buildPersonHome(String show, String url) { return TextSpan( text: show, style: TextStyle( decoration: TextDecoration.underline, ), recognizer: TapGestureRecognizer() ..onTap = () async { if (await canLaunch(url)) { UmengAnalyticsPlugin.event(AnalyticsConstant.aboutClick, label: show); await launch(url); } }, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/home_page.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/ota_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/app/utils/toast.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/views/bg/weather_main_bg.dart'; import 'package:flutter_dynamic_weather/views/common/loading_view.dart'; import 'package:flutter_dynamic_weather/views/pages/home/main_app_bar.dart'; import 'package:flutter_dynamic_weather/views/pages/home/main_message.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:location_permissions/location_permissions.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; class HomePage extends StatefulWidget { @override _HomePageState createState() => _HomePageState(); HomePage({Key key}) : super(key: key); } class _HomePageState extends State<HomePage> with AutomaticKeepAliveClientMixin { var locationState; Future<void> init() async { await UmengAnalyticsPlugin.init( androidKey: '5f43cf00b4b08b653e98cc1a', iosKey: '5f43cf6db4b08b653e98cc1f', channel: "github", ); UmengAnalyticsPlugin.event(AnalyticsConstant.initMainPage, label: Platform.operatingSystem); } @override void initState() { weatherPrint("umeng init event ${Platform.operatingSystem}"); init(); OTAUtils.initOTA(); super.initState(); } Widget _buildHomeContent(List<CityModel> cityModels) { weatherPrint("build home content: ${cityModels?.length}"); return Column( children: [ MainAppBar(cityModels: cityModels), Expanded( child: MainMessage(), ) ], ); } Future<void> requestPermission() async { await Future.delayed(Duration(seconds: 2)); var permissionStatus = await LocationPermissions().checkPermissionStatus(); weatherPrint('当前权限状态:$permissionStatus'); if (permissionStatus != PermissionStatus.granted) { var permissionResult = await LocationPermissions().requestPermissions( permissionLevel: LocationPermissionLevel.locationWhenInUse); if (permissionResult == PermissionStatus.granted) { await Future.delayed(Duration(seconds: 1)); setState(() { locationState = LocatePermissionState.success; }); } else { var models = await SPUtil.getCityModels(); if (models == null || models.isEmpty) { Navigator.of(context).pushNamed(WeatherRouter.search); } ToastUtils.show("请打开定位权限", context, duration: 2); } } else { setState(() { locationState = LocatePermissionState.success; }); } } @override Widget build(BuildContext context) { // 初始化 ScreenUtil.init( // 设备像素大小(必须在首页中获取) BoxConstraints( maxWidth: MediaQuery.of(context).size.width, maxHeight: MediaQuery.of(context).size.height, ), Orientation.portrait, // 设计尺寸 designSize: Size(750, 1334), allowFontScaling: false, ); return Scaffold( body: Stack( children: [ WeatherMainBg(), Container( padding: EdgeInsets.only( top: MediaQueryData.fromWindow(WidgetsBinding.instance.window) .padding .top), child: BlocBuilder<CityBloc, CityState>( builder: (_, s) { weatherPrint( 'homePage, state: ${s.runtimeType}, locationState: $locationState'); if (s is CitySuccess) { return _buildHomeContent(s.cityModels); } else if (s is CityInit) { if (locationState == null) { locationState = LocatePermissionState.loading; requestPermission(); } else if (locationState == LocatePermissionState.success) { BlocProvider.of<CityBloc>(context) .add(RequestLocationEvent()); } return Container( alignment: Alignment.center, child: Container(), ); } else if (s is LocationSuccessState) { return Container( alignment: Alignment.center, child: Container(), ); } return StateView(weatherState: ViewState.loading); }, )), ], ), ); } @override bool get wantKeepAlive => true; } enum LocatePermissionState { success, loading, failed, }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/life_index.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/time_util.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/app/res/common_extension.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; import 'package:url_launcher/url_launcher.dart'; class LifeIndexView extends StatelessWidget { List<LifeIndexDetail> lifeIndexDetail = []; WeatherModelResultDailyLifeIndex modelResultDailyLifeIndex; final String skycon; LifeIndexView({Key key, this.modelResultDailyLifeIndex, this.skycon}) : super(key: key) { if (modelResultDailyLifeIndex != null) { if (modelResultDailyLifeIndex.ultraviolet != null && modelResultDailyLifeIndex.ultraviolet.isNotEmpty) { modelResultDailyLifeIndex.ultraviolet.forEach((element) { var time = element.date.dateTime; var now = DateTime.now(); if (time.day == now.day) { lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.ultraviolet, element.desc, element.date)); } }); modelResultDailyLifeIndex.carWashing.forEach((element) { var time = element.date.dateTime; var now = DateTime.now(); if (time.day == now.day) { lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.carWashing, element.desc, element.date)); } }); modelResultDailyLifeIndex.dressing.forEach((element) { var time = element.date.dateTime; var now = DateTime.now(); if (time.day == now.day) { lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.dressing, element.desc, element.date)); } }); modelResultDailyLifeIndex.comfort.forEach((element) { var time = element.date.dateTime; var now = DateTime.now(); if (time.day == now.day) { lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.comfort, element.desc, element.date)); } }); modelResultDailyLifeIndex.coldRisk.forEach((element) { var time = element.date.dateTime; var now = DateTime.now(); if (time.day == now.day) { lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.coldRisk, element.desc, element.date)); } }); lifeIndexDetail.add(LifeIndexDetail( LifeIndexType.typhoon, "详情", "")); } } } Widget _buildBottomSheetIndexItem(BuildContext context, LifeIndexDetail detail) { String showTime = "${TimeUtil.getWeatherDayDesc(detail.date)}"; return GestureDetector( child: Container( child: Column( children: <Widget>[ Image.asset( WeatherUtils.getLifeIndexIcon(detail.type), width: 30, height: 30, color: Colors.white, ), SizedBox( height: 15, ), Text( detail.desc, style: TextStyle(color: Colors.white, fontSize: 16), ), SizedBox( height: 8, ), Text( showTime, style: TextStyle(color: Colors.white54, fontSize: 13), ), ], ), ) ); } Widget _buildLifeIndexItem(BuildContext context, LifeIndexDetail detail) { return InkWell( child: Container( child: Column( children: <Widget>[ Image.asset( WeatherUtils.getLifeIndexIcon(detail.type), width: 30, height: 30, color: Colors.white, ), SizedBox( height: 15, ), Text( detail.desc, style: TextStyle(color: Colors.white, fontSize: 16), ), SizedBox( height: 8, ), Text( WeatherUtils.getLifeIndexDesc(detail.type), style: TextStyle(color: Colors.white54, fontSize: 13), ), ], ), ), onTap: () { if (detail.type != LifeIndexType.typhoon) { UmengAnalyticsPlugin.event(AnalyticsConstant.bottomSheet, label: "生活指数"); showMaterialModalBottomSheet( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30)), ), backgroundColor: Colors.transparent, context: context, builder: (context) => BlurRectWidget( color: WeatherUtils.getColor(WeatherUtils.convertWeatherType(skycon))[0].withAlpha(60), child: Container( height: 0.5.sh, child: _buildSheetWidget(context, detail.type), ), ), ); } else { UmengAnalyticsPlugin.event(AnalyticsConstant.bottomSheet, label: "台风路径"); _launchURL(); } }, ); } _launchURL() async { const url = 'http://typhoon.zjwater.gov.cn/wap.htm'; if (await canLaunch(url)) { await launch(url); } } Widget _buildSheetWidget(BuildContext context, LifeIndexType lifeIndexType) { List<LifeIndexDetail> detail = []; if (modelResultDailyLifeIndex != null) { if (modelResultDailyLifeIndex.ultraviolet != null && modelResultDailyLifeIndex.ultraviolet.isNotEmpty) { if (lifeIndexType == LifeIndexType.ultraviolet) { modelResultDailyLifeIndex.ultraviolet.forEach((element) { detail.add(LifeIndexDetail( LifeIndexType.ultraviolet, element.desc, element.date)); }); } if (lifeIndexType == LifeIndexType.carWashing) { modelResultDailyLifeIndex.carWashing.forEach((element) { detail.add(LifeIndexDetail( LifeIndexType.carWashing, element.desc, element.date)); }); } if (lifeIndexType == LifeIndexType.dressing) { modelResultDailyLifeIndex.dressing.forEach((element) { detail.add(LifeIndexDetail( LifeIndexType.dressing, element.desc, element.date)); }); } if (lifeIndexType == LifeIndexType.comfort) { modelResultDailyLifeIndex.comfort.forEach((element) { detail.add(LifeIndexDetail( LifeIndexType.comfort, element.desc, element.date)); }); } if (lifeIndexType == LifeIndexType.coldRisk) { modelResultDailyLifeIndex.coldRisk.forEach((element) { detail.add(LifeIndexDetail( LifeIndexType.coldRisk, element.desc, element.date)); }); } } } var width = 1.0.sw / 3; var height = (0.5.sh - 30) / 2; var ratio = width / height; weatherPrint("bottomSheet width: $width, height: $height, ratio: $ratio"); return Container( margin: EdgeInsets.only(top: 30), child: GridView.count( childAspectRatio: ratio, physics: NeverScrollableScrollPhysics(), crossAxisCount: 3, children: detail .map((e) => _buildBottomSheetIndexItem(context, e)) .toList(), ), ); } @override Widget build(BuildContext context) { var itemWidth = (1.sw - DimenConstant.mainMarginStartEnd * 2) / 3 * 5 / 4; return BlurRectWidget( child: Container( height: itemWidth * (1 + 1), child: GridView.count( childAspectRatio: 4.0 / 5, physics: NeverScrollableScrollPhysics(), crossAxisCount: 3, children: lifeIndexDetail .map((e) => _buildLifeIndexItem(context, e)) .toList(), ), ), ); } } class LifeIndexDetail { LifeIndexType type; String desc; String date; LifeIndexDetail(this.type, this.desc, this.date); }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/sun_rise_set.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/ui_utils.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:path_drawing/path_drawing.dart'; import 'dart:ui' as ui; class SunSetRiseView extends StatelessWidget { final WeatherModelResultDailyAstro model; const SunSetRiseView({ Key key, this.model, }) : super(key: key); Widget _buildWidget() { if (model != null && model.sunrise != null && model.sunset != null) { return Column( children: [ Container( height: 140, width: 1.sw - DimenConstant.mainMarginStartEnd * 2, child: CustomPaint( painter: SunSetRisePainter(model.sunrise.time, model.sunset.time), ), ), Row( mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [ Container( margin: EdgeInsets.only(left: 20), child: Text( "日出 ${model.sunrise.time}", style: TextStyle(color: Colors.white), ), ), Container( margin: EdgeInsets.only(right: 20), child: Text( "日落 ${model.sunset.time}", style: TextStyle(color: Colors.white), ), ) ], ), SizedBox( height: 20, ), ], ); } return Container(); } @override Widget build(BuildContext context) { return _buildWidget(); } } class SunSetRisePainter extends CustomPainter { final String sunriseTime; final String sunsetTime; double ratio; double marginTop = -40; double marginBottom = 20; double marginLeftRight = 20; Paint _paint = Paint(); Path _path = Path(); int getMinute(String time) { if (time != null && time.isNotEmpty) { int hour = int.parse(time.split(":")[0]); int minute = int.parse(time.split(":")[1]); return hour * 60 + minute; } return 0; } SunSetRisePainter(this.sunriseTime, this.sunsetTime) { int sunriseMinute = getMinute(sunriseTime); int sunsetMinute = getMinute(sunsetTime); int nowMinute = DateTime.now().hour * 60 + DateTime.now().minute; int resultMinute = max(sunriseMinute, min(sunsetMinute, nowMinute)); ratio = (resultMinute - sunriseMinute).toDouble() / (sunsetMinute - sunriseMinute); weatherPrint( "SunSetRisePainter || $sunriseMinute, $sunsetMinute, $nowMinute, ratio: $ratio"); } @override void paint(Canvas canvas, Size size) { var height = size.height; var width = size.width; double startX = marginLeftRight; double startY = height - marginBottom; double endX = width - marginLeftRight; double endY = startY; _path.reset(); _path.moveTo(startX, startY); _path.quadraticBezierTo(width / 2, marginTop, endX, endY); _paint.color = Colors.white; _paint.style = PaintingStyle.stroke; _paint.strokeWidth = 1.5; canvas.drawPath( dashPath(_path, dashArray: CircularIntervalList<double>([10, 5])), _paint); var metrics = _path.computeMetrics(); var pm = metrics.elementAt(0); Offset sunOffset = pm.getTangentForOffset(pm.length * ratio).position; canvas.save(); canvas.clipRect(Rect.fromLTWH(0, 0, sunOffset.dx, height)); canvas.drawPath(_path, _paint); canvas.restore(); _paint.style = PaintingStyle.fill; _paint.color = Colors.yellow; canvas.drawCircle(sunOffset, 6, _paint); var now = DateTime.now(); String nowTimeStr = "${now.hour}:${now.minute}"; var nowTimePara = UiUtils.getParagraph(nowTimeStr, 14); canvas.drawParagraph(nowTimePara, Offset(sunOffset.dx - nowTimePara.width / 2, sunOffset.dy + 10)); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/city_view.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/res/widget_state.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/bloc/weather/weather_bloc.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/common/loading_view.dart'; import 'package:flutter_dynamic_weather/views/pages/home/aqi_chart.dart'; import 'package:flutter_dynamic_weather/views/pages/home/day_forecast.dart'; import 'package:flutter_dynamic_weather/views/pages/home/day_forecast_detail.dart'; import 'package:flutter_dynamic_weather/views/pages/home/hour_forecast.dart'; import 'package:flutter_dynamic_weather/views/pages/home/life_index.dart'; import 'package:flutter_dynamic_weather/views/pages/home/real_time.dart'; import 'package:flutter_dynamic_weather/views/pages/home/real_time_detail.dart'; import 'package:location_permissions/location_permissions.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; class CityView extends StatefulWidget { final CityModel cityModel; const CityView({Key key, @required this.cityModel}) : super(key: key); @override _CityViewState createState() => _CityViewState(); } class _CityViewState extends State<CityView> with AutomaticKeepAliveClientMixin { WeatherModelEntity _modelEntity; ScrollController _controller; StreamSubscription _subscription; WidgetState _state = WidgetState.loading; Future<void> refresh() async { weatherPrint("开始获取当前城市的数据 ${widget.cityModel.displayedName}"); BlocProvider.of<WeatherBloc>(context) .add(FetchWeatherDataEvent(widget.cityModel)); } Widget _buildCityContent() { weatherPrint('build city content, state: $_state'); if (_state == WidgetState.success) { weatherPrint("创建单个城市数据"); return RefreshIndicator( onRefresh: () async { refresh(); }, child: SingleChildScrollView( controller: _controller, physics: BouncingScrollPhysics(), child: Container( padding: EdgeInsets.symmetric( horizontal: DimenConstant.cardMarginStartEnd), child: Column( mainAxisSize: MainAxisSize.max, crossAxisAlignment: CrossAxisAlignment.stretch, children: [ RealtimeView(entity: _modelEntity, cityModel: widget.cityModel,), AqiChartView(entity: _modelEntity), SizedBox( height: DimenConstant.dayForecastMarginBottom, ), DayForecastView(resultDaily: _modelEntity?.result?.daily, modelEntity: _modelEntity,), SizedBox( height: DimenConstant.dayForecastMarginBottom, ), SizedBox( height: DimenConstant.dayForecastMarginBottom, ), SizedBox( height: 10, ), HourForecastView( resultHourly: _modelEntity?.result?.hourly, ), SizedBox( height: 30, ), RealTimeDetailView(entity: _modelEntity,), SizedBox( height: 30, ), LifeIndexView( modelResultDailyLifeIndex: _modelEntity?.result?.daily?.lifeIndex, skycon: _modelEntity?.result?.realtime?.skycon, ), SizedBox( height: 10, ), Container( child: Row( mainAxisAlignment: MainAxisAlignment.center, children: [ Image.asset("assets/images/caiyun.png", width: 40, height: 40, color: Colors.white54,), SizedBox(width: 10,), Text("数据来自彩云科技", style: TextStyle(color: Colors.white54),), ], ), ), SizedBox( height: 10, ), ], ), ), ), ); } else if (_state == WidgetState.error) { return StateView( weatherState: ViewState.error, ); } else { return StateView(weatherState: ViewState.loading); } } @override Widget build(BuildContext context) { return BlocListener<WeatherBloc, WeatherState>( listener: (_, state) { weatherPrint("城市页面收到事件 state: ${state.runtimeType}"); if (state is WeatherSuccess) { weatherPrint( 'success-current flag: ${widget.cityModel.cityFlag}, target flag: ${state.cityModel.cityFlag}'); if (state.cityModel.cityFlag == widget.cityModel.cityFlag) { setState(() { _state = WidgetState.success; _modelEntity = state.entity; }); } } else if (state is WeatherLoading) { weatherPrint( 'success-current flag: ${widget.cityModel.cityFlag}, target flag: ${state.cityModel}'); if (state.cityModel != null && state.cityModel.cityFlag == widget.cityModel.cityFlag && _modelEntity == null) { setState(() { _state = WidgetState.loading; }); } } else if (state is WeatherFailed) { weatherPrint( 'fail-current flag: ${widget.cityModel.cityFlag}, target flag: ${state.cityModel.cityFlag}'); if (state.cityModel.cityFlag == widget.cityModel.cityFlag && _modelEntity == null) { setState(() { _state = WidgetState.error; }); } } }, child: _buildCityContent(), ); } @override void initState() { weatherPrint('initState-${widget.cityModel.cityFlag}'); getDataFromCache(); refresh(); double initValue = 0; if (offsetNotifier.value != null) { initValue = offsetNotifier.value; } weatherPrint("init-value: $initValue"); _controller = ScrollController(initialScrollOffset: initValue); _controller.addListener(() { offsetNotifier.value = _controller.offset; }); _subscription = eventBus.on<ChangeMainAppBarIndexEvent>().listen((event) { if (offsetNotifier.value != null && event.cityFlag == widget.cityModel.cityFlag) { _controller.jumpTo(offsetNotifier.value); } }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } Future<void> getDataFromCache() async { weatherPrint("city view: getDataFromCache"); SPUtil.getAllWeatherModels().then((value) { var key = LocationUtil.convertCityFlag( widget.cityModel.cityFlag, widget.cityModel.isLocated); weatherPrint("city view: $key"); if (value != null && value.isNotEmpty) { var modelStr = value[key]; if (modelStr == null || modelStr == "") { return; } setState(() { _state = WidgetState.success; _modelEntity = WeatherModelEntity().fromJson(json.decode(modelStr)); }); weatherPrint("城市页面从缓存获取数据成功 $_modelEntity"); } }); } @override bool get wantKeepAlive => true; }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/main_message.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/common/loading_view.dart'; import 'package:flutter_dynamic_weather/views/pages/home/city_view.dart'; class MainMessage extends StatefulWidget { @override _MainMessageState createState() => _MainMessageState(); } class _MainMessageState extends State<MainMessage> { List<CityModel> _cityModels; PageController _controller = PageController(); StreamSubscription _subscription; Widget _buildMainWidget() { weatherPrint('main-build main widget'); if (_cityModels == null) { return StateView(weatherState: ViewState.loading); } else if (_cityModels.isEmpty) { return StateView(weatherState: ViewState.empty); } else { weatherPrint("创建城市列表页面"); weatherPrint('main-success, cityModel: $_cityModels'); return PageView.builder( controller: _controller, onPageChanged: (index) { weatherPrint('current index: $index'); eventBus.fire(ChangeMainAppBarIndexEvent(index, _cityModels[index].cityFlag)); }, itemBuilder: (context, index) { return CityView( cityModel: _cityModels[index], ); }, itemCount: _cityModels.length, ); } } @override void initState() { _subscription = eventBus.on<ChangeCityEvent>().listen((event) { if (_cityModels != null) { _cityModels.forEach((element) { if (element.cityFlag == event.cityFlag) { var index = _cityModels.indexOf(element); if (index >= 0 && index < _cityModels.length) { _controller.jumpToPage(index); } } }); } }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { var state = BlocProvider.of<CityBloc>(context).state; weatherPrint('build || main-state: ${state.runtimeType}'); if (state is CitySuccess) { _cityModels = state.cityModels; } return BlocListener<CityBloc, CityState>( listener: (_, state) { weatherPrint('BlocListener || main-state: ${state.runtimeType}'); if (state is CitySuccess) { setState(() { _cityModels = state.cityModels; }); } }, child: _buildMainWidget(), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/day_forecast.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/time_util.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_dynamic_weather/views/pages/home/day_forecast_detail.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; class DayForecastView extends StatelessWidget { final WeatherModelResultDaily resultDaily; final WeatherModelEntity modelEntity; DayForecastView({Key key, @required this.resultDaily, this.modelEntity}) : super(key: key); String _getWeatherDesc(int index) { if (resultDaily == null || resultDaily.skycon08h20h == null || resultDaily.skycon08h20h.isEmpty || index >= resultDaily.skycon08h20h.length) { return ""; } if (resultDaily.skycon20h32h == null || resultDaily.skycon20h32h.isEmpty || index >= resultDaily.skycon20h32h.length) { return ""; } var dayDesc = WeatherUtils.convertDesc(resultDaily.skycon08h20h[index].value); var nightDesc = WeatherUtils.convertDesc(resultDaily.skycon20h32h[index].value); if (dayDesc == nightDesc) { return "$dayDesc"; } return "$dayDesc转$nightDesc"; } String _getTemperatureDesc(int index) { if (resultDaily == null || resultDaily.temperature == null || resultDaily.temperature.isEmpty || index >= resultDaily.temperature.length) { return ""; } var dayTemperature = resultDaily.temperature[index].max; var nightTemperature = resultDaily.temperature[index].min; return "$dayTemperature°/$nightTemperature°"; } String _getWeatherDayDesc(int index) { if (resultDaily == null) { return ""; } return "${TimeUtil.getWeatherDayDesc(resultDaily.temperature[index].date)}"; } String _getAqiDesc(int index) { if (resultDaily == null || resultDaily.airQuality == null || resultDaily.airQuality.aqi == null || resultDaily.airQuality.aqi.isEmpty || index >= resultDaily.airQuality.aqi.length) { return ""; } return "${WeatherUtils.getAqiDesc(resultDaily.airQuality.aqi[index].max.chn)}"; } Widget _buildDayItemWidget(BuildContext context, int index) { var itemWidth = (1.sw - DimenConstant.cardMarginStartEnd * 2 - DimenConstant.dayMiddleMargin) / 2; return GestureDetector( onTap: () { UmengAnalyticsPlugin.event(AnalyticsConstant.bottomSheet, label: "多日"); showMaterialModalBottomSheet( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30)), ), backgroundColor: Colors.transparent, context: context, builder: (context) => BlurRectWidget( color: WeatherUtils.getColor(WeatherUtils.convertWeatherType( modelEntity?.result?.realtime?.skycon))[0] .withAlpha(60), child: Container( height: 0.5.sh, child: DayForecastDetail( resultDaily: modelEntity?.result?.daily, ), ), ), ); }, child: BlurRectWidget( child: Container( padding: EdgeInsets.symmetric(horizontal: 13), width: itemWidth, child: Column( mainAxisAlignment: MainAxisAlignment.spaceAround, children: [ Row( children: [ Container( width: 50, child: Text(_getWeatherDayDesc(index), style: TextStyle( color: Colors.white, fontSize: 17, fontWeight: FontWeight.bold, letterSpacing: 1)), ), Expanded( child: Container( child: Text("${_getWeatherDesc(index)}", textAlign: TextAlign.end, style: TextStyle( color: Colors.white, fontSize: 17, fontWeight: FontWeight.bold, letterSpacing: 1)), ), ) ], ), Row( children: [ Expanded( child: Container( child: Text("${_getTemperatureDesc(index)}", style: TextStyle( color: Colors.white, fontSize: 19, letterSpacing: 0.2, fontWeight: FontWeight.w600)), ), ), Container( width: 60, child: Text(_getAqiDesc(index), textAlign: TextAlign.end, style: TextStyle( color: Colors.white, fontSize: 14, fontWeight: FontWeight.w800)), ), ], ), ], ), ), ), ); } @override Widget build(BuildContext context) { return Container( child: Row( children: [ Container( child: _buildDayItemWidget(context, 0), height: DimenConstant.singleDayForecastHeight, ), SizedBox( width: DimenConstant.dayMiddleMargin, ), Container( child: _buildDayItemWidget(context, 1), height: DimenConstant.singleDayForecastHeight, ) ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/real_time_temp.dart
import 'dart:async'; import 'dart:io'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/pages/home/speak_anim.dart'; import 'package:flutter_tts/flutter_tts.dart'; class RealTimeTempView extends StatefulWidget { final String temp; final String content; RealTimeTempView({Key key, this.temp, this.content}) : super(key: key); @override _RealTimeTempViewState createState() => _RealTimeTempViewState(); } enum TtsState { playing, stopped, paused, continued } class _RealTimeTempViewState extends State<RealTimeTempView> { FlutterTts _flutterTts; TtsState ttsState = TtsState.stopped; StreamSubscription _subscription; @override void initState() { initTts(); _subscription = eventBus.on<TtsStatusEvent>().listen((event) { setState(() { ttsState = event.ttsState; }); }); super.initState(); } initTts() { _flutterTts = FlutterTts(); _flutterTts.setLanguage("zh"); if (!kIsWeb) { if (Platform.isAndroid) { _getEngines(); } } _flutterTts.setStartHandler(() { weatherPrint("Playing"); updateStatus(TtsState.playing); }); _flutterTts.setCompletionHandler(() { weatherPrint("Complete"); updateStatus(TtsState.stopped); }); _flutterTts.setCancelHandler(() { weatherPrint("Cancel"); updateStatus(TtsState.stopped); }); if (kIsWeb || Platform.isIOS) { _flutterTts.setPauseHandler(() { weatherPrint("Paused"); updateStatus(TtsState.paused); }); _flutterTts.setErrorHandler((msg) { weatherPrint("error: $msg"); updateStatus(TtsState.stopped); }); } } Future _getEngines() async { var engines = await _flutterTts.getEngines; if (engines != null) { for (dynamic engine in engines) { weatherPrint(engine); } } } void updateStatus(TtsState status) { setState(() => ttsState = status); eventBus.fire(TtsStatusEvent(status)); } Future _speak() async { if (widget.content != null) { if (widget.content.isNotEmpty) { weatherPrint("content: ${widget.content}"); var result = await _flutterTts.speak(widget.content); if (result == 1) updateStatus(TtsState.playing); } } } Future _stop() async { var result = await _flutterTts.stop(); if (result == 1) updateStatus(TtsState.stopped); } @override void dispose() { _flutterTts.stop(); _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { var color = Colors.white; return GestureDetector( child: Container( child: Row( mainAxisAlignment: MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.start, children: [ SizedBox( width: 10, ), Text( "${widget.temp}", style: TextStyle( fontSize: 150, fontWeight: FontWeight.w400, color: color), ), Text( "°", style: TextStyle( fontSize: 50, fontWeight: FontWeight.w500, color: color), ), Container( alignment: Alignment(1, 0.9), width: 30, height: 150, child: AnimatedCrossFade( firstChild: Image.asset( "assets/images/play.png", color: color, ), secondChild: SpeakAnim(), crossFadeState: ttsState == TtsState.playing ? CrossFadeState.showSecond : CrossFadeState.showFirst, duration: Duration(milliseconds: 150), ), ), ], ), ), onTap: () { if (ttsState != TtsState.playing) { _speak(); } else { _stop(); } }, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/speak_anim.dart
import 'dart:math'; import 'package:flutter/material.dart'; class SpeakAnim extends StatefulWidget { @override _SpeakAnimState createState() => _SpeakAnimState(); } class _SpeakAnimState extends State<SpeakAnim> with SingleTickerProviderStateMixin { AnimationController _controller; Animation<double> animation; @override void initState() { _controller = new AnimationController( vsync: this, duration: Duration(seconds: 6)); animation = Tween<double>(begin: 0, end: 30).animate(_controller) ..addListener(() { setState(() {}); }); _controller.repeat(); super.initState(); } @override void deactivate() { _controller.stop(); super.deactivate(); } @override void dispose() { _controller.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Container( child: CustomPaint( painter: SpeakPainter(animation.value), size: Size(25, 15), ), ); } } class SpeakPainter extends CustomPainter { final double itemWidth = 3; Paint _paint = Paint(); final double value; SpeakPainter(this.value); @override void paint(Canvas canvas, Size size) { var width = size.width; var height = size.height; _paint.color = Colors.white; _paint.style = PaintingStyle.fill; _paint.isAntiAlias = true; double startX = -width; int count = width ~/ itemWidth; for (int i = 0; i < count; i++) { double x = startX + itemWidth * 2 * i + value; double y = (sin(x) + 1) * height / 3 + height / 3; canvas.drawRRect(RRect.fromLTRBAndCorners(x, height - y, x + itemWidth, height, topLeft: Radius.circular(4), topRight: Radius.circular(4)), _paint); } } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/aqi_chart.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/ui_utils.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'dart:ui' as ui; class AqiChartView extends StatelessWidget { final WeatherModelEntity entity; const AqiChartView({ Key key, @required this.entity, }) : super(key: key); @override Widget build(BuildContext context) { var width = (1.sw - DimenConstant.cardMarginStartEnd * 2 - DimenConstant.dayMiddleMargin) / 2; var height = DimenConstant.aqiChartHeight; int aqiValue = entity?.result?.realtime?.airQuality?.aqi?.chn; String aqiValueStr = aqiValue == null ? "0" : "$aqiValue"; double aqiRatio = aqiValue == null ? 0 : aqiValue.toDouble() / 500; double humidityValue = entity?.result?.realtime?.humidity ?? 0; String humidityStr = "${(humidityValue * 100).toInt()}%"; return Row( children: [ BlurRectWidget( child: Container( width: width, height: height, child: CustomPaint( painter: AqiChartPainter(aqiRatio, aqiValueStr, entity?.result?.realtime?.airQuality?.description?.chn), ), ), ), SizedBox( width: DimenConstant.dayMiddleMargin, ), BlurRectWidget( child: Container( width: width, height: height, child: CustomPaint( painter: AqiChartPainter(humidityValue, humidityStr, "体感"), ), ), ), ], ); } } class AqiChartPainter extends CustomPainter { Paint _paint = Paint(); Path _path = Path(); double ratio; String value; String desc; AqiChartPainter(this.ratio, this.value, this.desc); @override void paint(Canvas canvas, Size size) { weatherPrint("AqiChartPainter size:$size"); var radius = size.height / 2 - 10; var centerX = size.width / 2; var centerY = size.height / 2; var centerOffset = Offset(centerX, centerY); // 绘制半透明圆弧 _path.reset(); _path.addArc(Rect.fromCircle(center: centerOffset, radius: radius), pi * 0.7, pi * 1.6); _paint.style = PaintingStyle.stroke; _paint.strokeWidth = 4; _paint.strokeCap = StrokeCap.round; _paint.color = Colors.white38; canvas.drawPath(_path, _paint); // 绘制纯白色圆弧 _path.reset(); _path.addArc(Rect.fromCircle(center: centerOffset, radius: radius), pi * 0.7, pi * 1.6 * ratio); _paint.color = Colors.white; canvas.drawPath(_path, _paint); // 绘制 AQIValue var valuePara = UiUtils.getParagraph(value, 30); canvas.drawParagraph( valuePara, Offset(centerOffset.dx - valuePara.width / 2, centerOffset.dy - valuePara.height / 2)); // 绘制 AQIDesc var descPara = UiUtils.getParagraph("$desc", 15); canvas.drawParagraph( descPara, Offset(centerOffset.dx - valuePara.width / 2, centerOffset.dy + valuePara.height / 2)); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/hour_forecast.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/ui_utils.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/app/res/common_extension.dart'; import 'dart:ui' as ui; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; class HourForecastView extends StatelessWidget { final WeatherModelResultHourly resultHourly; List<HourData> _hourData = []; HourForecastView({Key key, @required this.resultHourly}) : super(key: key) { if (resultHourly != null && resultHourly.temperature != null && resultHourly.temperature.isNotEmpty) { resultHourly.temperature.forEach((element) { int index = resultHourly.temperature.indexOf(element); DateTime targetTime = element.datetime.dateTime; String showTime = "${targetTime.hour.gapTime}:${targetTime.minute.gapTime}"; int temperature = element.value; WeatherType weatherType = WeatherType.sunny; double windDirection; double speed; int aqiValue; String skycon; if (resultHourly.skycon != null && resultHourly.skycon.isNotEmpty) { weatherType = WeatherUtils.convertWeatherType(resultHourly.skycon[index].value); skycon = resultHourly.skycon[index].value; } if (resultHourly.wind != null && resultHourly.wind.isNotEmpty) { windDirection = resultHourly.wind[index].direction; speed = resultHourly.wind[index].speed; } if (resultHourly.wind != null && resultHourly.wind.isNotEmpty) { windDirection = resultHourly.wind[index].direction; speed = resultHourly.wind[index].speed; } if (resultHourly.airQuality != null && resultHourly.airQuality.aqi != null && resultHourly.airQuality.aqi.isNotEmpty) { aqiValue = resultHourly.airQuality.aqi[index].value.chn; } _hourData.add(HourData(showTime, temperature, weatherType, windDirection, speed, aqiValue, skycon)); }); weatherPrint("获取到小时数据为: $_hourData"); } } String completionGap(int src) { return src < 10 ? "0$src" : "$src"; } @override Widget build(BuildContext context) { return Container( child: BlurRectWidget( child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: CustomPaint( painter: MyPaint(_hourData), size: Size(_hourData.length * 50.toDouble(), 200), ), scrollDirection: Axis.horizontal, ), )); } } class MyPaint extends CustomPainter { final List<HourData> _hourData; double itemWidth; double itemHeight = 80; double circleRadius = 2; double temTextSize = 14; double temTextMarginBottom = 5; // 温度距离折线的距离 double showTimeMarginTop = 5; // 时间距离折线顶部的距离 double iconHeight = 25; // 直线预留底部的距离 double iconMargin = 10; int maxTem, minTem; Map<int, HourData> _weatherTypes = {}; List<Offset> _bgOffset = []; Path _path = Path(); Paint _paint = Paint(); Path _bgPath = Path(); Paint _bgPaint = Paint(); MyPaint(this._hourData); void setMinMax() { if (maxTem == null || minTem == null) { minTem = maxTem = _hourData[0].temperature; _hourData.forEach((element) { if (element.temperature > maxTem) { maxTem = element.temperature; } if (element.temperature < minTem) { minTem = element.temperature; } }); weatherPrint("setMinMax== min: $minTem, max: $maxTem"); } } void initWeatherType() { if (_weatherTypes.isEmpty) { HourData lastHourData = _hourData[0]; _weatherTypes[0] = lastHourData; _hourData.forEach((element) { int index = _hourData.indexOf(element); if (element.weatherType != lastHourData.weatherType) { _weatherTypes[index] = element; lastHourData = element; } if (index == _hourData.length - 1) { _weatherTypes[index] = element; } }); weatherPrint("total weather types: $_weatherTypes"); } } @override void paint(Canvas canvas, Size size) { setMinMax(); initWeatherType(); _paint.color = Colors.white; itemWidth = size.width / _hourData.length; double gapHeight = itemHeight / (maxTem - minTem); _path.reset(); double startX = itemWidth / 2; double startY = temTextSize + temTextMarginBottom * 2; _bgOffset.clear(); _hourData.forEach((element) { int index = _hourData.indexOf(element); double x = startX + index * itemWidth; double y = startY + itemHeight - (element.temperature - minTem) * gapHeight; var temperatureParagraph = UiUtils.getParagraph("${element.temperature}°", temTextSize, itemWidth: itemWidth); canvas.drawParagraph( temperatureParagraph, Offset(x - temperatureParagraph.width / 2, y - temperatureParagraph.height - temTextMarginBottom)); var offset = Offset(x, y); if (index == 0) { _path.moveTo(x, y); } else { _path.lineTo(x, y); _paint.style = PaintingStyle.fill; canvas.drawCircle(offset, circleRadius, _paint); } _bgOffset.add(offset); // 绘制展示时间 var showTimeParagraph = UiUtils.getParagraph("${element.showTime}", temTextSize, itemWidth: itemWidth); canvas.drawParagraph( showTimeParagraph, Offset( x - showTimeParagraph.width / 2, startY + itemHeight + showTimeMarginTop + iconHeight + iconMargin * 2)); // 添加背景点 }); _paint.style = PaintingStyle.stroke; _paint.strokeWidth = 2; _paint.strokeCap = StrokeCap.round; _paint.strokeJoin = StrokeJoin.round; canvas.drawPath(_path, _paint); drawWeatherTypeBg(canvas, size); } /// 绘制天气类型 void drawWeatherTypeBg(Canvas canvas, Size size) { weatherPrint("_weatherTypes.keys: ${_weatherTypes.keys}"); bool flag = true; int lastIndex; double bottomY = temTextSize + temTextMarginBottom * 2 + itemHeight + iconHeight + iconMargin * 2; _bgPaint.style = PaintingStyle.fill; _weatherTypes.forEach((index, hourData) { if (lastIndex != null) { var offsets = _bgOffset.sublist(lastIndex, index + 1); _bgPath.reset(); offsets.forEach((element) { int index = offsets.indexOf(element); if (index == 0) { _bgPath.moveTo(element.dx, bottomY); } _bgPath.lineTo(element.dx, element.dy); if (index == offsets.length - 1) { _bgPath.lineTo(element.dx, bottomY); _bgPath.close(); } }); double middleX = (offsets.first.dx + offsets.last.dx) / 2; double middleY = temTextSize + temTextMarginBottom * 2 + itemHeight + iconMargin; var image = weatherImages[hourData.weatherType]; canvas.save(); double scale = iconHeight / image.height; canvas.scale(scale); var iconOffset = Offset(middleX / scale - image.width / 2 * scale, middleY / scale); canvas.drawImage(image, iconOffset, _paint); canvas.restore(); flag = !flag; var gradient = ui.Gradient.linear( Offset(0, temTextSize + temTextMarginBottom * 2), Offset( 0, temTextSize + temTextMarginBottom * 2 + itemHeight + iconHeight + iconMargin * 3), <Color>[ flag ? const Color(0xFFffffff) : const Color(0x88FFffff), const Color(0x00FFFFFF) ], ); _bgPaint.shader = gradient; canvas.drawPath(_bgPath, _bgPaint); } lastIndex = index; }); } @override bool shouldRepaint(MyPaint oldDelegate) { return false; } } class HourData { String showTime; int temperature; WeatherType weatherType; double windDirection; double speed; int aqiValue; String skycon; HourData(this.showTime, this.temperature, this.weatherType, this.windDirection, this.speed, this.aqiValue, this.skycon); @override String toString() { return 'HourData{showTime: $showTime, temperature: $temperature, weatherType: $weatherType, windDirection: $windDirection, speed: $speed, aqiValue: $aqiValue}'; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/real_time.dart
import 'dart:io'; import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_dynamic_weather/views/pages/home/rain_detail.dart'; import 'package:flutter_dynamic_weather/views/pages/home/real_time_temp.dart'; import 'package:modal_bottom_sheet/modal_bottom_sheet.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class RealtimeView extends StatelessWidget { final WeatherModelEntity entity; final CityModel cityModel; const RealtimeView({ Key key, @required this.entity, this.cityModel }) : super(key: key); String buildSpeakContent() { String introduction = "简悦天气为您播报天气,"; String cityName = ""; if (cityModel != null) { cityName = cityModel.displayedName + ","; } String weatherType = "今天白天到夜间,${_getWeatherDesc()},"; String temp = _getTemperatureDesc(); String aqi = ""; var chn = entity?.result?.realtime?.airQuality?.description?.chn; if (chn != null) { aqi = "空气质量 $chn"; } return introduction + cityName + weatherType + temp + aqi; } String _getWeatherDesc() { if (entity.result.daily == null || entity.result.daily.skycon08h20h == null || entity.result.daily.skycon08h20h.isEmpty) { return ""; } if (entity.result.daily.skycon20h32h == null || entity.result.daily.skycon20h32h.isEmpty) { return ""; } var dayDesc = WeatherUtils.convertDesc(entity.result.daily.skycon08h20h[0].value); var nightDesc = WeatherUtils.convertDesc(entity.result.daily.skycon20h32h[0].value); if (dayDesc == nightDesc) { return "$dayDesc"; } return "$dayDesc转$nightDesc"; } String _getTemperatureDesc() { if (entity.result.daily == null || entity.result.daily.temperature == null || entity.result.daily.temperature.isEmpty) { return ""; } var dayTemperature = entity.result.daily.temperature[0].max; var nightTemperature = entity.result.daily.temperature[0].min; return "最高温$dayTemperature摄氏度,最低温$nightTemperature摄氏度,"; } @override Widget build(BuildContext context) { var realTimeWidgetHeight = MediaQuery.of(context).size.height - DimenConstant.singleDayForecastHeight - DimenConstant.aqiChartHeight - DimenConstant.dayForecastMarginBottom * 2 - kToolbarHeight - MediaQueryData.fromWindow(WidgetsBinding.instance.window).padding.top; realTimeWidgetHeight = max(realTimeWidgetHeight, DimenConstant.realtimeMinHeight); weatherPrint('realtime height: $realTimeWidgetHeight'); var child; if (entity != null && entity.result != null && entity.result.realtime != null) { UmengAnalyticsPlugin.event(AnalyticsConstant.weatherType, label: WeatherUtils.convertDesc(entity.result.realtime.skycon)); child = Column( mainAxisAlignment: MainAxisAlignment.end, crossAxisAlignment: CrossAxisAlignment.start, children: [ RealTimeTempView(temp: entity.result.realtime.temperature?.toString(), content: buildSpeakContent(),), Container( margin: EdgeInsets.only(left: 20), width: 220, child: Text( "${WeatherUtils.convertDesc(entity.result.realtime.skycon)}", style: TextStyle( fontSize: 20, fontWeight: FontWeight.bold, color: Colors.white), ), ), SizedBox( height: 20, ), GestureDetector( onTap: (){ UmengAnalyticsPlugin.event(AnalyticsConstant.bottomSheet, label: "降雨卡片"); if (Platform.isAndroid) { WeatherRouter.jumpToNativePage(WeatherRouter.minute); } else { showMaterialModalBottomSheet( shape: RoundedRectangleBorder( borderRadius: BorderRadius.only( topLeft: Radius.circular(30), topRight: Radius.circular(30)), ), backgroundColor: Colors.transparent, context: context, builder: (context) => BlurRectWidget( color: WeatherUtils.getColor( WeatherUtils.convertWeatherType( entity.result.realtime.skycon))[0].withAlpha( 60), child: Container( height: 0.3.sh, child: RainDetailView(location: entity.location, title: "${entity.result.forecastKeypoint}",), ), ), ); } }, child: Container( margin: EdgeInsets.only(left: 20), child: Row( children: [ Text( "${entity.result.forecastKeypoint}", style: TextStyle( fontSize: 15, color: Colors.white, fontWeight: FontWeight.bold), ), Icon( Icons.chevron_right, color: Colors.white, ), ], ), ), ), SizedBox( height: 40, ), ], ); } return Container( height: realTimeWidgetHeight, child: child, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/real_time_detail.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; import 'package:flutter_dynamic_weather/views/pages/home/sun_rise_set.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class RealTimeDetailView extends StatelessWidget { final WeatherModelEntity entity; const RealTimeDetailView({ Key key, @required this.entity, }) : super(key: key); Widget _buildSunSetRiseWidget() { List<WeatherModelResultDailyAstro> astro = entity?.result?.daily?.astro; if (astro == null || astro.isEmpty) { return Container(); } return SunSetRiseView(model: entity?.result?.daily?.astro[0]); } Widget _buildItem(String title, String desc) { var width = (1.sw - DimenConstant.cardMarginStartEnd * 2 - 60) / 2; return Container( width: width, height: width / 2, child: Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text( title, style: TextStyle(color: Color(0x99ffffff), fontSize: 14), ), SizedBox( height: 8, ), Text( desc, style: TextStyle(color: Color(0xffffffff), fontSize: 18), ) ], ), ); } Widget _buildBottomWidget() { const defaultStr = "--"; String apparentTemp = defaultStr; String humidity = defaultStr; String pressure = defaultStr; String wind = defaultStr; String pm25 = defaultStr; String ultraviolet = defaultStr; if (entity != null && entity.result != null && entity.result.realtime != null) { var realtime = entity.result.realtime; if (realtime.apparentTemperature != null) { apparentTemp = "${realtime.apparentTemperature.toInt()}°"; } if (realtime.humidity != null) { humidity = "${(realtime.humidity * 100).toInt()}%"; } if (realtime.pressure != null) { pressure = "${realtime.pressure}hPa"; } if (realtime.wind != null && realtime.wind.speed != null) { wind = "${realtime.wind.speed}km/h"; } if (realtime.airQuality != null && realtime.airQuality.pm25 != null) { pm25 = "${realtime.airQuality.pm25}"; } if (realtime.lifeIndex != null && realtime.lifeIndex.ultraviolet != null) { ultraviolet = "${realtime.lifeIndex.ultraviolet.index}"; } } return Container( padding: EdgeInsets.symmetric(horizontal: 30), child: Column( children: [ Row( children: [ _buildItem("体感", apparentTemp), _buildItem("湿度", humidity), ], ), Row( children: [ _buildItem("气压", pressure), _buildItem("风速", wind), ], ), Row( children: [ _buildItem("PM25", pm25), _buildItem("紫外线", ultraviolet), ], ), ], ), ); } @override Widget build(BuildContext context) { return Container( child: BlurRectWidget( child: Column( children: [ _buildSunSetRiseWidget(), _buildBottomWidget(), ], ), ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/main_app_bar.dart
import 'dart:async'; import 'package:flutter/material.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; class MainAppBar extends StatefulWidget { final List<CityModel> cityModels; MainAppBar({Key key, this.cityModels}) : super(key: key); @override _MainAppBarState createState() => _MainAppBarState(); } class _MainAppBarState extends State<MainAppBar> { int _index = 0; StreamSubscription _subscription; Widget _buildAppBarTitle() { if (widget.cityModels == null || widget.cityModels.isEmpty) { return Container(); } if (_index >= widget.cityModels.length) { _index = widget.cityModels.length - 1; } int index = _index; if (index >= widget.cityModels.length) { index = _index - 1; } if (index >= widget.cityModels.length) { return Container(); } CityModel cityModel = widget.cityModels[index]; return Text( "${cityModel.displayedName}", style: TextStyle( color: Colors.white, fontWeight: FontWeight.bold, fontSize: 16), ); } bool isLocated(CityModel cityModel) { bool isLocated = false; if (widget.cityModels != null && widget.cityModels.isNotEmpty) { widget.cityModels.forEach((element) { if (element.isLocated == true && cityModel == element) { isLocated = true; } }); } return isLocated; } Widget _buildPointWidget() { if (widget.cityModels != null && widget.cityModels.length > 1) { return Row( mainAxisAlignment: MainAxisAlignment.center, children: widget.cityModels .map((e) => Container( margin: EdgeInsets.only(left: 3, top: 3), child: Icon( isLocated(e) ? Icons.location_on : Icons.brightness_1, size: isLocated(e) ? 10 : 5, color: widget.cityModels.indexOf(e) == _index ? Colors.white : Colors.white54, ), )) .toList(), ); } return Container(); } @override void initState() { _subscription = eventBus.on<ChangeMainAppBarIndexEvent>().listen((event) { weatherPrint("收到 event ${event.index}"); setState(() { _index = event.index; }); }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { return Container( height: kToolbarHeight, child: Row( children: [ IconButton( padding: EdgeInsets.only(left: 20), onPressed: () async { if (widget.cityModels == null && widget.cityModels.isEmpty) { Navigator.of(context).pushNamed(WeatherRouter.search); } else { Navigator.of(context).pushNamed(WeatherRouter.manager); } }, icon: Icon( Icons.add, color: Colors.white, ), ), Expanded( child: Container( child: Column( mainAxisAlignment: MainAxisAlignment.center, children: [ _buildAppBarTitle(), _buildPointWidget(), ], ), ), ), IconButton( padding: EdgeInsets.only(right: 20), onPressed: () { Navigator.of(context).pushNamed(WeatherRouter.about); }, icon: Icon( Icons.more_vert, color: Colors.white, size: 20, ), ) ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/day_forecast_detail.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/time_util.dart'; import 'package:flutter_dynamic_weather/app/utils/ui_utils.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/app/res/common_extension.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'dart:ui' as ui; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; class DayForecastDetail extends StatelessWidget { List<DaysData> _data = []; DayForecastDetail({Key key, @required WeatherModelResultDaily resultDaily}) : super(key: key) { if (resultDaily != null && resultDaily.skycon != null && resultDaily.skycon.isNotEmpty) { resultDaily.skycon.forEach((element) { int index = resultDaily.skycon.indexOf(element); String time; String time1; WeatherType dayType; WeatherType nightType; String daySkycon; String nightSkycon; int dayTemp; int nightTemp; double windSpeed; double windDirection; DateTime targetTime = element.date.dateTime; time1 = "${targetTime.month}月${targetTime.day}日"; time = TimeUtil.getWeatherDayDesc(element.date); if (resultDaily.temperature != null && index < resultDaily.temperature.length) { dayTemp = resultDaily.temperature[index].max; nightTemp = resultDaily.temperature[index].min; } if (resultDaily.skycon08h20h != null && index < resultDaily.skycon08h20h.length) { dayType = WeatherUtils.convertWeatherType( resultDaily.skycon08h20h[index].value); daySkycon = resultDaily.skycon08h20h[index].value; } if (resultDaily.skycon20h32h != null && index < resultDaily.skycon20h32h.length) { nightType = WeatherUtils.convertWeatherType( resultDaily.skycon20h32h[index].value); nightSkycon = resultDaily.skycon20h32h[index].value; } if (resultDaily.wind != null && index < resultDaily.wind.length) { var wind = resultDaily.wind[index]; if (wind.avg != null) { windSpeed = wind.avg.speed; windDirection = wind.avg.direction; } } _data.add(DaysData(time, time1, dayType, nightType, dayTemp, nightTemp, windSpeed, windDirection, daySkycon, nightSkycon)); }); } weatherPrint("daysData: $_data"); } @override Widget build(BuildContext context) { return Container( child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: CustomPaint( painter: DayPainter(_data), size: Size(_data.length * 100.toDouble(), 0.5.sh), ), scrollDirection: Axis.horizontal, ), ); } } class DayPainter extends CustomPainter { final List<DaysData> _data; int topMaxTemp = 0, topMinTemp = 100; int bottomMaxTemp = 0, bottomMinTemp = 100; double mainTextSize = 14; double subTextSize = 10; double margin1 = 20; double margin2 = 15; double margin3 = 30; double tempTextSize = 14; double topLineStartY, topLineEndY; double bottomLineStartY, bottomLineEndY; double lineHeight; double iconSize = 30; double itemWith = 100; Paint _paint = Paint(); Path _topPath = Path(); Path _bottomPath = Path(); void setMinMax() { _data.forEach((element) { if (element.dayTemp > topMaxTemp) { topMaxTemp = element.dayTemp; } if (element.dayTemp < topMinTemp) { topMinTemp = element.dayTemp; } if (element.nightTemp > bottomMaxTemp) { bottomMaxTemp = element.nightTemp; } if (element.nightTemp < bottomMinTemp) { bottomMinTemp = element.nightTemp; } }); weatherPrint("setMinMax1== min: $topMinTemp, max: $topMaxTemp"); weatherPrint("setMinMax2== min: $bottomMinTemp, max: $bottomMaxTemp"); } DayPainter(this._data) { setMinMax(); lineHeight = (0.5.sh - mainTextSize * 3 - subTextSize * 2 - margin1 * 2 - margin2 * 4 - margin3 * 4 - tempTextSize * 2 - iconSize * 2) / 2; topLineStartY = margin2 * 2 + margin3 * 2 + margin1 + mainTextSize * 2 + tempTextSize + subTextSize + iconSize; topLineEndY = topLineStartY + lineHeight; bottomLineStartY = topLineEndY + margin1; bottomLineEndY = bottomLineStartY + lineHeight; } @override void paint(Canvas canvas, Size size) { double startX = itemWith / 2; double startY = margin3; _topPath.reset(); _bottomPath.reset(); _data.forEach((element) { int index = _data.indexOf(element); var timePara = UiUtils.getParagraph(element.time, mainTextSize, itemWidth: itemWith); canvas.drawParagraph( timePara, Offset(startX - timePara.width / 2, startY)); double time1Y = startY + margin1 + mainTextSize; var time1Para = UiUtils.getParagraph(element.time1, subTextSize, itemWidth: itemWith); canvas.drawParagraph( time1Para, Offset(startX - time1Para.width / 2, time1Y)); var dayIconY = time1Y + margin3; var dayImage = weatherImages[element.dayType]; var scale = iconSize / dayImage.width; var dayIconOffset = Offset(startX / scale - dayImage.width / 2, dayIconY / scale); canvas.save(); canvas.scale(scale); canvas.drawImage(dayImage, dayIconOffset, _paint); canvas.restore(); var dayDescY = dayIconY + iconSize + margin2; var dayPara = UiUtils.getParagraph( WeatherUtils.convertDesc(element.daySkycon), mainTextSize, itemWidth: itemWith); canvas.drawParagraph( dayPara, Offset(startX - dayPara.width / 2, dayDescY)); var nightIconY = bottomLineEndY + tempTextSize + margin2; var nightImage = weatherImages[element.dayType]; var nightIconOffset = Offset(startX / scale - nightImage.width / 2, nightIconY / scale); canvas.save(); canvas.scale(scale); canvas.drawImage(nightImage, nightIconOffset, _paint); canvas.restore(); var nightDescY = nightIconY + iconSize + margin2; var nightPara = UiUtils.getParagraph( WeatherUtils.convertDesc(element.nightSkycon), mainTextSize, itemWidth: itemWith); canvas.drawParagraph( nightPara, Offset(startX - nightPara.width / 2, nightDescY)); _paint.color = Colors.white; var topOffset = Offset(startX, getTopLineY(element.dayTemp)); var bottomOffset = Offset(startX, getBottomLineY(element.dayTemp)); _paint.style = PaintingStyle.fill; // 绘制折线上的圆点 canvas.drawCircle(topOffset, 3, _paint); canvas.drawCircle(bottomOffset, 3, _paint); // 绘制圆点上下的温度值 var topTempPara = UiUtils.getParagraph("${element.dayTemp}°", mainTextSize, itemWidth: itemWith); canvas.drawParagraph( topTempPara, Offset(topOffset.dx - topTempPara.width / 2, topOffset.dy - topTempPara.height - 5)); var bottomTempPara = UiUtils.getParagraph("${element.dayTemp}°", mainTextSize, itemWidth: itemWith); canvas.drawParagraph( bottomTempPara, Offset(bottomOffset.dx - bottomTempPara.width / 2, bottomOffset.dy + 5)); // 绘制折线 if (index == 0) { _topPath.moveTo(topOffset.dx, topOffset.dy); _bottomPath.moveTo(bottomOffset.dx, bottomOffset.dy); } else { _topPath.lineTo(topOffset.dx, topOffset.dy); _bottomPath.lineTo(bottomOffset.dx, bottomOffset.dy); } startX += itemWith; }); _paint.strokeWidth = 2; _paint.style = PaintingStyle.stroke; canvas.drawPath(_topPath, _paint); canvas.drawPath(_bottomPath, _paint); } getTopLineY(int temp) { if (temp == topMaxTemp) { return topLineStartY; } return topLineStartY + (topMaxTemp - temp) / (topMaxTemp - topMinTemp) * lineHeight; } getBottomLineY(int temp) { if (temp == bottomMaxTemp) { return bottomLineStartY; } return bottomLineStartY + (bottomMaxTemp - temp) / (bottomMaxTemp - bottomMinTemp); } @override bool shouldRepaint(CustomPainter oldDelegate) { return false; } } class DaysData { String time; String time1; WeatherType dayType; WeatherType nightType; int dayTemp; int nightTemp; double windSpeed; double windDirection; String daySkycon; String nightSkycon; DaysData( this.time, this.time1, this.dayType, this.nightType, this.dayTemp, this.nightTemp, this.windSpeed, this.windDirection, this.daySkycon, this.nightSkycon); @override String toString() { return 'DaysData{time: $time, time1: $time1, dayType: $dayType, nightType: $nightType, dayTemp: $dayTemp, nightTemp: $nightTemp, windSpeed: $windSpeed, windDirection: $windDirection}'; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/test.dart
import 'dart:async'; import 'dart:io' show Platform; import 'package:flutter/foundation.dart' show kIsWeb; import 'package:flutter/material.dart'; import 'package:flutter_tts/flutter_tts.dart'; void main() => runApp(MyApp()); class MyApp extends StatefulWidget { @override _MyAppState createState() => _MyAppState(); } enum TtsState { playing, stopped, paused, continued } class _MyAppState extends State<MyApp> { FlutterTts flutterTts; dynamic languages; String language; double volume = 0.5; double pitch = 1.0; double rate = 0.5; String _newVoiceText; TtsState ttsState = TtsState.stopped; get isPlaying => ttsState == TtsState.playing; get isStopped => ttsState == TtsState.stopped; get isPaused => ttsState == TtsState.paused; get isContinued => ttsState == TtsState.continued; @override initState() { super.initState(); initTts(); } initTts() { flutterTts = FlutterTts(); _getLanguages(); if (!kIsWeb) { if (Platform.isAndroid) { _getEngines(); } } flutterTts.setStartHandler(() { setState(() { print("Playing"); ttsState = TtsState.playing; }); }); flutterTts.setCompletionHandler(() { setState(() { print("Complete"); ttsState = TtsState.stopped; }); }); flutterTts.setCancelHandler(() { setState(() { print("Cancel"); ttsState = TtsState.stopped; }); }); if (kIsWeb || Platform.isIOS) { flutterTts.setPauseHandler(() { setState(() { print("Paused"); ttsState = TtsState.paused; }); }); flutterTts.setContinueHandler(() { setState(() { print("Continued"); ttsState = TtsState.continued; }); }); } flutterTts.setErrorHandler((msg) { setState(() { print("error: $msg"); ttsState = TtsState.stopped; }); }); } Future _getLanguages() async { languages = await flutterTts.getLanguages; if (languages != null) setState(() => languages); } Future _getEngines() async { var engines = await flutterTts.getEngines; if (engines != null) { for (dynamic engine in engines) { print(engine); } } } Future _speak() async { await flutterTts.setVolume(volume); await flutterTts.setSpeechRate(rate); await flutterTts.setPitch(pitch); if (_newVoiceText != null) { if (_newVoiceText.isNotEmpty) { var result = await flutterTts.speak(_newVoiceText); if (result == 1) setState(() => ttsState = TtsState.playing); } } } Future _stop() async { var result = await flutterTts.stop(); if (result == 1) setState(() => ttsState = TtsState.stopped); } Future _pause() async { var result = await flutterTts.pause(); if (result == 1) setState(() => ttsState = TtsState.paused); } @override void dispose() { super.dispose(); flutterTts.stop(); } List<DropdownMenuItem<String>> getLanguageDropDownMenuItems() { var items = List<DropdownMenuItem<String>>(); for (dynamic type in languages) { items.add( DropdownMenuItem(value: type as String, child: Text(type as String))); } return items; } void changedLanguageDropDownItem(String selectedType) { setState(() { language = selectedType; flutterTts.setLanguage(language); }); } void _onChange(String text) { setState(() { _newVoiceText = text; }); } @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Flutter TTS'), ), body: SingleChildScrollView( scrollDirection: Axis.vertical, child: Column(children: [ _inputSection(), _btnSection(), languages != null ? _languageDropDownSection() : Text(""), _buildSliders() ])))); } Widget _inputSection() => Container( alignment: Alignment.topCenter, padding: EdgeInsets.only(top: 25.0, left: 25.0, right: 25.0), child: TextField( onChanged: (String value) { _onChange(value); }, )); Widget _btnSection() { if (!kIsWeb && Platform.isAndroid) { return Container( padding: EdgeInsets.only(top: 50.0), child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ _buildButtonColumn(Colors.green, Colors.greenAccent, Icons.play_arrow, 'PLAY', _speak), _buildButtonColumn( Colors.red, Colors.redAccent, Icons.stop, 'STOP', _stop), ])); } else { return Container( padding: EdgeInsets.only(top: 50.0), child: Row(mainAxisAlignment: MainAxisAlignment.spaceEvenly, children: [ _buildButtonColumn(Colors.green, Colors.greenAccent, Icons.play_arrow, 'PLAY', _speak), _buildButtonColumn( Colors.red, Colors.redAccent, Icons.stop, 'STOP', _stop), _buildButtonColumn( Colors.blue, Colors.blueAccent, Icons.pause, 'PAUSE', _pause), ])); } } Widget _languageDropDownSection() => Container( padding: EdgeInsets.only(top: 50.0), child: Row(mainAxisAlignment: MainAxisAlignment.center, children: [ DropdownButton( value: language, items: getLanguageDropDownMenuItems(), onChanged: changedLanguageDropDownItem, ) ])); Column _buildButtonColumn(Color color, Color splashColor, IconData icon, String label, Function func) { return Column( mainAxisSize: MainAxisSize.min, mainAxisAlignment: MainAxisAlignment.center, children: [ IconButton( icon: Icon(icon), color: color, splashColor: splashColor, onPressed: () => func()), Container( margin: const EdgeInsets.only(top: 8.0), child: Text(label, style: TextStyle( fontSize: 12.0, fontWeight: FontWeight.w400, color: color))) ]); } Widget _buildSliders() { return Column( children: [_volume(), _pitch(), _rate()], ); } Widget _volume() { return Slider( value: volume, onChanged: (newVolume) { setState(() => volume = newVolume); }, min: 0.0, max: 1.0, divisions: 10, label: "Volume: $volume"); } Widget _pitch() { return Slider( value: pitch, onChanged: (newPitch) { setState(() => pitch = newPitch); }, min: 0.5, max: 2.0, divisions: 15, label: "Pitch: $pitch", activeColor: Colors.red, ); } Widget _rate() { return Slider( value: rate, onChanged: (newRate) { setState(() => rate = newRate); }, min: 0.0, max: 1.0, divisions: 10, label: "Rate: $rate", activeColor: Colors.green, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/home/rain_detail.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/ui_utils.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/common/loading_view.dart'; import 'dart:ui' as ui; const rainTitleSize = 16.0; const rainTitleHeight = 60.0; class RainDetailView extends StatefulWidget { final List<double> location; final String title; RainDetailView({Key key, this.location, this.title}) : super(key: key); @override _RainDetailViewState createState() => _RainDetailViewState(); } class _RainDetailViewState extends State<RainDetailView> with SingleTickerProviderStateMixin { List<double> _precipitation; AnimationController _controller; double _ratio = 0.0; Future<void> fetchMinuteData() async { var res = await WeatherApi().loadMinuteData(widget.location[1].toString(), widget.location[0].toString()); weatherPrint("$res"); try { List<double> precipitation = List<double>.from(res["result"]["minutely"]["precipitation_2h"]); if (precipitation != null && precipitation.isNotEmpty) { setState(() { _precipitation = precipitation; }); Future.delayed(Duration(milliseconds: 200)).then((value) => { _controller.forward() }); } } catch (e) { weatherPrint(e.toString()); setState(() { _precipitation = []; }); } } @override void initState() { fetchMinuteData(); _controller = AnimationController(duration: Duration(milliseconds: 250), vsync: this); CurvedAnimation(parent: _controller, curve: Curves.linear); _controller.addListener(() { setState(() { _ratio = _controller.value; }); }); super.initState(); } @override void dispose() { _controller.dispose(); super.dispose(); } Widget _buildWidget() { if (_precipitation == null) { return StateView(weatherState: ViewState.loading,); } else if (_precipitation.isEmpty) { return StateView(weatherState: ViewState.error,); } else { return Container( child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ Container( height: rainTitleHeight, alignment: Alignment.center, child: Text(widget.title, style: TextStyle(fontSize: rainTitleSize, color: Colors.white, fontWeight: FontWeight.bold),), ), Expanded( child: CustomPaint( painter: RainPainter(_precipitation, _ratio), ), ) ], ), ); } } @override Widget build(BuildContext context) { return _buildWidget(); } } class RainPainter extends CustomPainter { Paint _paint = Paint(); Paint _linePaint = Paint(); Path _linePath = Path(); final double _ratio; double _marginLeft = 30; double _marginRight = 30; double _marginBottom = 60; double _timeMarginTop = 10; double _textSize = 12; List<double> _data; RainPainter(List<double> data, this._ratio){ if (data != null && data.isNotEmpty) { bool isEmpty = true; for(final item in data) { if (item != 0.0) { isEmpty = false; } } if (isEmpty == false) { _data = data; } } } @override void paint(Canvas canvas, Size size) { drawLine(canvas, size); drawBg(canvas, size); } void drawLine(Canvas canvas, Size size) { if (_data != null && _data.isNotEmpty) { double width = size.width - _marginLeft - _marginRight; double height = size.height - _marginBottom; double startX = _marginLeft; double itemWidth = width / 120; double itemHeight = height / 100; _linePath.reset(); for (int i = 0; i < _data.length; i++) { double y = height - _data[i] * 100 * itemHeight * _ratio; double x = startX + i * itemWidth; if (i == 0) { _linePath.moveTo(x, y); } else { _linePath.lineTo(x, y); } } var gradient = ui.Gradient.linear( Offset(0, 0), Offset(0, height), <Color>[ const Color(0xFFffffff), const Color(0x00FFFFFF) ], ); _linePaint.style = PaintingStyle.stroke; _linePaint.strokeWidth = 1; _linePaint.color = Colors.white; canvas.drawPath(_linePath, _linePaint); _linePath.lineTo(width + startX, height); _linePath.lineTo(startX, height); _linePath.close(); _linePaint.style = PaintingStyle.fill; _linePaint.shader = gradient; canvas.drawPath(_linePath, _linePaint); } } void drawBg(Canvas canvas, Size size) { // 绘制背景 line double itemHeight = (size.height - _marginBottom) / 3; double bgLineWidth = size.width - _marginLeft - _marginRight; _paint.style = PaintingStyle.stroke; _paint.strokeWidth = 1; _paint.color = Colors.white.withAlpha(100); for (int i = 0; i < 4; i++) { var startOffset = Offset(_marginLeft, itemHeight * i); var endOffset = Offset(_marginLeft + bgLineWidth, itemHeight * i); canvas.drawLine(startOffset, endOffset, _paint); } // 绘制底部文字 var hourY = size.height - _marginBottom + _timeMarginTop; var nowPara = UiUtils.getParagraph("现在", _textSize, itemWidth: bgLineWidth / 3); canvas.drawParagraph(nowPara, Offset(_marginLeft - nowPara.width / 2, hourY)); var onePara = UiUtils.getParagraph("1小时后", _textSize, itemWidth: bgLineWidth / 3); canvas.drawParagraph(onePara, Offset(_marginLeft + bgLineWidth / 2 - onePara.width / 2, hourY)); var twoPara = UiUtils.getParagraph("2小时后", _textSize, itemWidth: bgLineWidth / 3); canvas.drawParagraph(twoPara, Offset(_marginLeft + bgLineWidth - twoPara.width / 2, hourY)); // 绘制左侧文字 var bigPara = UiUtils.getParagraph("大", _textSize); canvas.drawParagraph(bigPara, Offset(_marginLeft / 2 - bigPara.width / 2, 0)); var middlePara = UiUtils.getParagraph("中", _textSize); canvas.drawParagraph(middlePara, Offset(_marginLeft / 2 - middlePara.width / 2, itemHeight)); var smallPara = UiUtils.getParagraph("小", _textSize); canvas.drawParagraph(smallPara, Offset(_marginLeft / 2 - smallPara.width / 2, itemHeight * 2)); } @override bool shouldRepaint(CustomPainter oldDelegate) { return true; } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/manager/manager_page.dart
import 'dart:async'; import 'dart:convert'; import 'package:equatable/equatable.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_slidable/flutter_slidable.dart'; import 'package:flutter_weather_bg/bg/weather_color_bg.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; class ManagerPage extends StatefulWidget { @override _ManagerPageState createState() => _ManagerPageState(); } class _ManagerPageState extends State<ManagerPage> { List<ManagerData> _managerData; StreamSubscription _subscription; Future<void> fetchData() async { weatherPrint("开始获取城市列表数据"); List<ManagerData> managerData = []; List<CityModel> cityModels = await SPUtil.getCityModels(); Map<String, String> allWeatherData = await SPUtil.getAllWeatherModels(); if (cityModels != null && cityModels.isNotEmpty && allWeatherData != null && allWeatherData.isNotEmpty) { cityModels.forEach((element) { String key = "${LocationUtil.convertCityFlag(element.cityFlag, element.isLocated)}"; if (allWeatherData.containsKey(key)) { var modelStr = allWeatherData[key]; if (modelStr != null && modelStr.isNotEmpty) { WeatherModelEntity weatherModelEntity = WeatherModelEntity().fromJson(json.decode(modelStr)); String currentTemperature = ""; if (weatherModelEntity != null && weatherModelEntity.result != null && weatherModelEntity.result.realtime != null) { currentTemperature = "${weatherModelEntity.result.realtime.temperature}°"; } String todayTemperature = ""; if (weatherModelEntity != null && weatherModelEntity.result != null && weatherModelEntity.result.daily != null) { todayTemperature = "${WeatherUtils.getTemperatureDesc(weatherModelEntity.result.daily)}"; } WeatherType weatherType = WeatherType.sunny; if (weatherModelEntity != null && weatherModelEntity.result != null && weatherModelEntity.result.realtime != null) { weatherType = WeatherUtils.convertWeatherType( weatherModelEntity.result.realtime.skycon); } String weatherDesc = ""; if (weatherModelEntity != null && weatherModelEntity.result != null && weatherModelEntity.result.realtime != null) { weatherDesc = WeatherUtils.convertDesc( weatherModelEntity.result.realtime.skycon); } managerData.add(ManagerData( cityFlag: element.cityFlag, isLocated: element.isLocated, cityName: element.displayedName, currentTemperature: currentTemperature, todayTemperature: todayTemperature, weatherType: weatherType, weatherDesc: weatherDesc, )); } } }); } weatherPrint( "获取城市管理列表数据成功 length: ${managerData.length} data: $managerData"); // managerData[0].weatherType = WeatherType.lightSnow; // managerData[1].weatherType = WeatherType.middleSnow; // managerData[2].weatherType = WeatherType.heavySnow; // managerData[3].weatherType = WeatherType.hazy; // managerData[4].weatherType = WeatherType.foggy; // managerData[5].weatherType = WeatherType.dusty; setState(() { _managerData = managerData; }); } @override void initState() { fetchData(); _subscription = eventBus.on<UpdateManagerData>().listen((event) async { await Future.delayed(Duration(milliseconds: 500)); fetchData(); }); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } Widget _buildAppBar() => Container( height: kToolbarHeight, child: Stack( children: [ Container( padding: EdgeInsets.only(left: 6), alignment: Alignment.centerLeft, child: IconButton( icon: Icon( Icons.arrow_back_ios, color: Colors.black54, size: 20, ), onPressed: () { Navigator.of(context).pop(); }, ), ), Align( child: Text( "城市管理", style: TextStyle(fontSize: 20), ), ) ], )); Widget _buildManagerContent() { if (_managerData != null) { var managerWidgetHeight = MediaQuery.of(context).size.height - kToolbarHeight - MediaQueryData.fromWindow(WidgetsBinding.instance.window) .padding .top - kToolbarHeight - 30; return Container( height: managerWidgetHeight, margin: EdgeInsets.only(left: 10, right: 10), child: ListView.separated( itemCount: _managerData.length, separatorBuilder: (_, index) => SizedBox( height: 10, ), itemBuilder: (_, index) => Card( elevation: 3, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20)), child: _buildItemWidget(_managerData[index])), ), ); } return Container(); } Widget _buildItemContentWidget(ManagerData data) { var radius = 20.0; return ClipPath( clipper: ShapeBorderClipper( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(radius))), child: Stack( children: [ WeatherBg( weatherType: data.weatherType, width: MediaQuery.of(context).size.width, height: 100, ), Container( height: 100, child: Row( children: [ SizedBox( width: 14, ), Expanded( child: Column( mainAxisSize: MainAxisSize.min, crossAxisAlignment: CrossAxisAlignment.start, children: [ Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( "${data.weatherDesc}", style: TextStyle( color: Color.fromARGB(200, 255, 255, 255), fontWeight: FontWeight.w500, letterSpacing: 1, fontSize: 12), ), SizedBox( width: 5, ), Text( "${data.todayTemperature}", style: TextStyle( color: Color.fromARGB(200, 255, 255, 255), fontWeight: FontWeight.w500, letterSpacing: 1, fontSize: 12), ), ], ), SizedBox( height: 5, ), Row( children: [ Text( "${data.cityName}", style: TextStyle( color: Color.fromARGB(250, 255, 255, 255), fontWeight: FontWeight.w400, fontSize: 18), ), SizedBox( width: 6, ), Visibility( visible: data.isLocated == true, child: Icon( Icons.location_on, color: Colors.white, size: 18, ), ) ], ), ], ), ), Text( "${data.currentTemperature}", style: TextStyle( color: Colors.white, fontWeight: FontWeight.w400, fontSize: 40), ), SizedBox( width: 20, ) ], ), ), ], ), ); } Widget _buildItemWidget(ManagerData data) { if (data.isLocated != true) { return Container( child: ClipPath( child: GestureDetector( child: Slidable( actionPane: SlidableDrawerActionPane(), actionExtentRatio: 0.25, child: _buildItemContentWidget(data), secondaryActions: <Widget>[ IconSlideAction( caption: '删除', color: Colors.red, icon: Icons.delete, onTap: () => {deleteCity(data)}, ), ], ), onTap: () async { eventBus.fire(ChangeCityEvent(data.cityFlag)); Navigator.of(context).pop(); }, ), clipper: ShapeBorderClipper( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20)))), ), ); } else { return Container( child: ClipPath( child: GestureDetector( child: _buildItemContentWidget(data), onTap: () async { eventBus.fire(ChangeCityEvent(data.cityFlag)); Navigator.of(context).pop(); }, ), clipper: ShapeBorderClipper( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all(Radius.circular(20)))), ), ); } } Future<void> deleteCity(ManagerData managerData) async { _managerData.remove(managerData); setState(() {}); BlocProvider.of<CityBloc>(context) .add(DeleteCityData(managerData.cityFlag)); } Widget _buildSearchView() { return Container( padding: EdgeInsets.only( top: 6, bottom: 6, left: DimenConstant.mainMarginStartEnd, right: DimenConstant.mainMarginStartEnd), height: kToolbarHeight, child: GestureDetector( child: Container( decoration: BoxDecoration( color: Color(0x30cccccc), borderRadius: BorderRadius.all(Radius.circular(100)), ), child: Row( children: [ SizedBox( width: 20, ), Icon( Icons.search, color: Colors.grey, ), SizedBox( width: 10, ), Text( "搜索城市天气", style: TextStyle(fontSize: 16, color: Color(0xA0000000)), ) ], ), ), onTap: () { Navigator.of(context).pushNamed(WeatherRouter.search); }, ), ); } @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: AnnotatedRegion<SystemUiOverlayStyle>( value: SystemUiOverlayStyle.dark, child: Container( padding: EdgeInsets.only( top: MediaQueryData.fromWindow(WidgetsBinding.instance.window) .padding .top), child: Column( children: [ _buildAppBar(), _buildSearchView(), _buildManagerContent(), ], ), ), )); } } class ManagerData extends Equatable { final String cityFlag; final String cityName; final String todayTemperature; final String currentTemperature; final bool isLocated; WeatherType weatherType; final String weatherDesc; ManagerData( {this.cityFlag, this.cityName, this.todayTemperature, this.currentTemperature, this.isLocated, this.weatherType, this.weatherDesc}); @override String toString() { return 'ManagerData{cityFlag: $cityFlag, cityName: $cityName, todayTemperature: $todayTemperature, currentTemperature: $currentTemperature, isLocated: $isLocated, weatherType: $weatherType, weatherDesc: $weatherDesc}'; } @override List<Object> get props => [cityFlag]; }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/search/search_list_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_data.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_app_bar.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_page.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; class SearchListView extends StatelessWidget { final List<CityData> cityData; final CityItemClickCallback itemClickCallback; final List<CityModel> cityModels; SearchListView({Key key, this.cityData, this.itemClickCallback, this.cityModels}) : super(key: key); bool isAdd(CityData cityData) { bool isAdd = false; if (cityModels != null && cityModels.isNotEmpty && cityData != null) { cityModels.forEach((element) { if (element.cityFlag == cityData.center) { isAdd = true; } }); } return isAdd; } @override Widget build(BuildContext context) { if (cityData != null && cityData.isNotEmpty) { weatherPrint("SearchListView || ${cityData.length}"); var searchWidgetHeight = MediaQuery.of(context).size.height - kToolbarHeight - MediaQueryData.fromWindow(WidgetsBinding.instance.window) .padding .top - 10; return Container( height: searchWidgetHeight, margin: EdgeInsets.symmetric(horizontal: 10), child: ListView.separated( itemBuilder: (_, index) { return Card( elevation: 3, shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(20)), child: GestureDetector( child: Container( height: 80, decoration: BoxDecoration( borderRadius: BorderRadius.circular(20), gradient: LinearGradient( colors: WeatherUtil.getColor(WeatherType.sunny), stops: [0, 1], begin: Alignment.topCenter, end: Alignment.bottomCenter, )), child: Row( children: [ SizedBox(width: 20), Expanded( child: Text("${cityData[index].name}", style: TextStyle(color: Colors.white, fontSize: 18, fontWeight: FontWeight.bold),), ), Text("${isAdd(cityData[index]) ? "已添加" : ""}", style: TextStyle(color: Colors.white, fontSize: 14),), SizedBox( width: 16, ) ], ), ), onTap: () { if (isAdd(cityData[index])) { eventBus.fire(ChangeCityEvent(cityData[index].center)); Navigator.of(context).pop(); } else if (itemClickCallback != null) { itemClickCallback(cityData[index]); } }, ), ); }, separatorBuilder: (_, index) => SizedBox(height: 10,), itemCount: cityData.length, physics: BouncingScrollPhysics(), ), ); } return Container(); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/search/search_page.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_bloc/flutter_bloc.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/res/widget_state.dart'; import 'package:flutter_dynamic_weather/app/router.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/app/utils/toast.dart'; import 'package:flutter_dynamic_weather/bloc/city/city_bloc.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_data.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/district_model_entity.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/common/loading_dialog.dart'; import 'package:flutter_dynamic_weather/views/common/loading_view.dart'; import 'package:flutter_dynamic_weather/views/pages/search/hot_city_view.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_app_bar.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_list_view.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; class SearchPage extends StatefulWidget { @override _SearchPageState createState() => _SearchPageState(); } class _SearchPageState extends State<SearchPage> { bool _hotViewVisible = true; bool _searchListVisible = false; List<CityData> _cityData; WidgetState _state; List<CityModel> cityModels; String _keyWords; Future<bool> _dealBack() async { if (cityModels == null || cityModels.isEmpty) { SystemNavigator.pop(animated: true); } else { Navigator.of(context).pop(); } return false; } @override void initState() { init(); super.initState(); } Future<void> init() async { cityModels = await SPUtil.getCityModels(); } Future<void> fetchCityData(keywords) async { setState(() { _searchListVisible = true; _state = WidgetState.loading; }); List<CityData> cityData = []; var result = await WeatherApi().searchCity(keywords); weatherPrint("search result $result"); if (keywords != _keyWords) { return; } if (result == null) { // 请求失败 weatherPrint("搜索失败"); setState(() { _state = WidgetState.error; _searchListVisible = false; }); } else { if (result.districts != null && result.districts.isNotEmpty) { UmengAnalyticsPlugin.event(AnalyticsConstant.searchCityName, label: "$keywords"); result.districts.forEach((element) { if (element.level == CityData.cityLevel || element.level == CityData.districtLevel) { cityData.add( CityData(element.name, element.center, level: element.level)); } var districts = element.districts; if (districts != null && districts.isNotEmpty) { districts.forEach((element) { if (element.level == CityData.cityLevel || element.level == CityData.districtLevel) { cityData.add(CityData(element.name, element.center, level: element.level)); } }); } }); } else if (result.info == "INVALID_REQUEST") { weatherPrint("高德 API 调用次数上限"); ToastUtils.show("由于高德 API 调用次数上限,无法搜索,请见谅", context, duration: 5, gravity: 2); } } if (cityData.isEmpty) { // 未搜索到 weatherPrint("未搜到数据"); setState(() { _state = WidgetState.error; }); } else { // 搜索成功 weatherPrint("搜索成功 $cityData"); setState(() { _state = WidgetState.success; _cityData = cityData; }); } } Widget _buildSearchContent() { weatherPrint("创建搜索内容 state: $_state"); if (_state == WidgetState.loading) { return StateView(); } else if (_state == WidgetState.error) { return Container( child: StateView(weatherState: ViewState.error,), ); } else { return SearchListView( cityData: _cityData, itemClickCallback: (data){ onItemClick(data, true); }, cityModels: cityModels, ); } } CityModel _buildDefault() { CityModel cityModel = CityModel( latitude: 39.904989, longitude: 116.405285, country: "中国", province: "北京市", district: "东城区", displayedName: "北京市", ); return cityModel; } Future<void> onItemClick(CityData cityData, bool fromList) async { showAppDialog(); var result = await WeatherApi().reGeo(cityData.center); weatherPrint("item click regeo result: $result"); if (result == null) { Navigator.of(context).pop(); ToastUtils.show("添加失败请重试", context); return; } CityModel cityModel = await parseCityModel(result, cityData); if (cityModel == null) { ToastUtils.show("高德 API 调用上限, 默认添加北京,请见谅", context, duration: 5); cityModel = _buildDefault(); } else { if (fromList) { cityModel.displayedName = "${WeatherUtils.getCityName(cityModel)}"; } else { cityModel.displayedName = cityData.name; } } BlocProvider.of<CityBloc>(context).add(InsertCityData(cityModel)); await Future.delayed(Duration(milliseconds: 20)); Navigator.of(context).pop(); await Future.delayed(Duration(milliseconds: 20)); Navigator.of(context).pop(); await Future.delayed(Duration(milliseconds: 200)); eventBus.fire(ChangeCityEvent(cityModel.cityFlag)); eventBus.fire(UpdateManagerData()); } static Future<CityModel> parseCityModel(result, CityData cityData) async { CityModel cityModel = CityModel(); if (result["regeocode"] != null && result["regeocode"]["addressComponent"] != null) { var addressComponent = result["regeocode"]["addressComponent"]; cityModel.longitude = double.parse(LocationUtil.parseFlag(cityData.center)[0]); cityModel.latitude = double.parse(LocationUtil.parseFlag(cityData.center)[1]); cityModel.country = addressComponent["country"]; cityModel.province = addressComponent["province"]; cityModel.district = addressComponent["district"]; if (addressComponent["city"] != null && addressComponent["city"] is String) { cityModel.city = addressComponent["city"]; } } else { return null; } return cityModel; } @override Widget build(BuildContext context) { return WillPopScope( child: Scaffold( resizeToAvoidBottomInset: false, body: Container( padding: EdgeInsets.only( top: MediaQueryData.fromWindow(WidgetsBinding.instance.window) .padding .top), child: Column( children: [ SearchAppBar( (value) async { _keyWords = value; if (value == null || value.isEmpty) { setState(() { _hotViewVisible = true; _searchListVisible = false; }); } else { setState(() { _hotViewVisible = false; }); await Future.delayed(Duration(milliseconds: 500)); fetchCityData(value); } }, cancelTapCallback: () { _dealBack(); }, searchTapCallback: (keywords) { fetchCityData(keywords); }, ), Stack( children: [ Visibility( visible: _hotViewVisible, child: HotCityView( itemClickCallback: (data){ onItemClick(data, false); }, ), ), Visibility( visible: _searchListVisible, child: _buildSearchContent(), ) ], ), ], ), )), onWillPop: _dealBack, ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/search/hot_city_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/Toast.dart'; import 'package:flutter_dynamic_weather/app/utils/color_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_data.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_app_bar.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_page.dart'; class HotCityView extends StatefulWidget { final CityItemClickCallback itemClickCallback; HotCityView({Key key, this.itemClickCallback}) : super(key: key); @override _HotCityViewState createState() => _HotCityViewState(); } class _HotCityViewState extends State<HotCityView> { List<CityData> _cityData; List<CityModel> cityModels; Widget _buildHotItem(BuildContext context, CityData cityData) { return Container( margin: EdgeInsets.only(left: 8, right: 8, top: 5, bottom: 5), child: ActionChip( padding: EdgeInsets.only(left: 16, right: 16, top: 10, bottom: 10), label: Text( "${cityData.name}", style: TextStyle(color: isAdd(cityData) ? Colors.blue : Colors.black), ), backgroundColor: ColorUtils.parse("#11000000"), onPressed: () async { if (isAdd(cityData)) { eventBus.fire(ChangeCityEvent(cityData.center)); Navigator.of(context).pop(); } else if (widget.itemClickCallback != null) { widget.itemClickCallback(cityData); } }, ), ); } bool isAdd(CityData cityData) { bool isAdd = false; if (cityModels != null && cityModels.isNotEmpty && cityData != null) { cityModels.forEach((element) { if (element.cityFlag == cityData.center) { isAdd = true; } }); } return isAdd; } Widget _buildHotView() { if (_cityData != null) { return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(left: 12), child: Text( "热门城市", style: TextStyle(color: ColorUtils.parse("#bb000000")), ), ), SizedBox( height: 10, ), Wrap( alignment: WrapAlignment.start, children: _cityData.map((e) => _buildHotItem(context, e)).toList(), ) ], ); } else { return null; } } Future<void> fetchHotData() async { _cityData = [ CityData("北京市", "116.405285,39.904989"), CityData("上海市", "121.472644,31.231706"), CityData("广州市", "113.280637,23.125178"), CityData("深圳市", "114.085947,22.547"), CityData("珠海市", "113.553986,22.224979"), CityData("佛山市", "113.122717,23.028762"), CityData("南京市", "118.767413,32.041544"), CityData("苏州市", "120.619585,31.299379"), CityData("厦门市", "118.11022,24.490474"), CityData("南宁市", "108.320004,22.82402"), CityData("成都市", "104.065735,30.659462"), CityData("长沙市", "112.982279,28.19409"), CityData("杭州市", "120.153576,30.287459"), CityData("武汉市", "114.298572,30.584355"), CityData("青岛市", "120.355173,36.082982"), CityData("西安市", "125.151424,42.920415"), CityData("太原市", "112.549248,37.857014"), CityData("石家庄市", "114.502461,38.045474"), CityData("重庆市", "106.504962,29.533155"), CityData("天津市", "117.190182,39.125596"), ]; cityModels = await SPUtil.getCityModels(); setState(() {}); } @override void initState() { fetchHotData(); super.initState(); } @override Widget build(BuildContext context) { return Container( child: _buildHotView(), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views/pages
mirrored_repositories/SimplicityWeather/lib/views/pages/search/search_app_bar.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/model/city_data.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_page.dart'; typedef CancelTapCallback = void Function(); typedef CancelSearchCallback = void Function(String keywords); typedef CityItemClickCallback = void Function(CityData cityData); class SearchAppBar extends StatefulWidget { final CancelTapCallback cancelTapCallback; final CancelSearchCallback searchTapCallback; final ValueChanged<String> onChanged; SearchAppBar(this.onChanged, {Key key, this.cancelTapCallback, this.searchTapCallback}) : super(key: key); @override _SearchAppBarState createState() => _SearchAppBarState(); } class _SearchAppBarState extends State<SearchAppBar> { TextEditingController _controller = TextEditingController(); String _buttonText = "取消"; bool closeVisible = false; @override void initState() { super.initState(); } @override Widget build(BuildContext context) { return Container( padding: EdgeInsets.only( top: 6, bottom: 6, left: DimenConstant.mainMarginStartEnd, right: DimenConstant.mainMarginStartEnd), height: kToolbarHeight, child: Row( children: <Widget>[ Expanded( child: Stack( children: [ TextField( onChanged: (value) { weatherPrint("value: $value"); widget.onChanged(value); if (value != null && value.isNotEmpty) { setState(() { _buttonText = "搜索"; closeVisible = true; }); } else { _buttonText = "取消"; closeVisible = false; } }, controller: _controller, autofocus: true, decoration: InputDecoration( prefixIcon: Icon( Icons.search, color: Colors.grey, ), contentPadding: EdgeInsets.only(top: 1, bottom: 1, left: 12), fillColor: Color(0x30cccccc), filled: true, enabledBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0x00FF0000)), borderRadius: BorderRadius.all(Radius.circular(100))), hintText: '搜索城市天气', focusedBorder: OutlineInputBorder( borderSide: BorderSide(color: Color(0x00000000)), borderRadius: BorderRadius.all(Radius.circular(100))), )), Visibility( visible: closeVisible, child: Align( alignment: Alignment(0.9, 0), child: IconButton( icon: Icon( Icons.clear, color: Colors.grey, ), onPressed: () { _controller.text = ""; if (widget.onChanged != null) { widget.onChanged(""); } setState(() { closeVisible = false; _buttonText = "取消"; }); }, ), ), ), ], ), ), SizedBox( width: DimenConstant.mainMarginStartEnd, ), GestureDetector( child: Text( _buttonText, style: TextStyle( color: Colors.blue, fontSize: 16, fontWeight: FontWeight.w500), ), onTap: () { if (_controller.text == null || _controller.text.isEmpty) { if (widget.cancelTapCallback != null) { widget.cancelTapCallback(); } } else { if (widget.searchTapCallback != null) { widget.searchTapCallback(_controller.text); } } }, ) ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/bg/weather_main_bg.dart
import 'dart:async'; import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; class WeatherMainBg extends StatefulWidget { @override _WeatherMainBgState createState() => _WeatherMainBgState(); } class _WeatherMainBgState extends State<WeatherMainBg> with SingleTickerProviderStateMixin { int _index = 0; StreamSubscription _subscription; List<WeatherType> _weatherTypes; double _value = 1; Future<void> fetchWeatherTypes() async { weatherPrint("天气背景开始获取数据..."); List<WeatherType> weatherTypes = []; List<CityModel> cityModels = await SPUtil.getCityModels(); Map<String, String> allWeatherData = await SPUtil.getAllWeatherModels(); if (cityModels != null && cityModels.isNotEmpty && allWeatherData != null && allWeatherData.isNotEmpty) { cityModels.forEach((element) { String key = "${LocationUtil.convertCityFlag(element.cityFlag, element.isLocated)}"; if (allWeatherData.containsKey(key)) { WeatherType weatherType = WeatherType.sunny; var modelStr = allWeatherData[key]; if (modelStr != null && modelStr.isNotEmpty) { WeatherModelEntity weatherModelEntity = WeatherModelEntity().fromJson(json.decode(modelStr)); if (weatherModelEntity != null && weatherModelEntity.result != null && weatherModelEntity.result.realtime != null) { weatherType = WeatherUtils.convertWeatherType( weatherModelEntity.result.realtime.skycon); } } weatherTypes.add(weatherType); } }); } // weatherTypes.clear(); // weatherTypes = [WeatherType.lightSnow, WeatherType.middleSnow, WeatherType.heavySnow]; // weatherTypes[0] = WeatherType.lightSnow; // weatherTypes[1] = WeatherType.middleSnow; // weatherTypes[2] = WeatherType.heavySnow; if (weatherTypes.isNotEmpty) { setState(() { _weatherTypes = weatherTypes; if (_index >= _weatherTypes.length) { _index = _weatherTypes.length - 1; } }); } } @override void initState() { _subscription = eventBus.on().listen((event) { if (event is ChangeMainAppBarIndexEvent) { _index = event.index; if (_weatherTypes != null && _weatherTypes.isNotEmpty && _index < _weatherTypes.length) { var type = _weatherTypes[_index]; } setState(() {}); } else if (event is MainBgChangeEvent) { fetchWeatherTypes(); } }); fetchWeatherTypes(); super.initState(); } @override void dispose() { _subscription.cancel(); super.dispose(); } @override Widget build(BuildContext context) { var width = MediaQuery.of(context).size.width; var height = MediaQuery.of(context).size.height; WeatherType weatherType = WeatherType.sunny; if (_weatherTypes != null && _weatherTypes.isNotEmpty) { weatherType = _weatherTypes[_index]; } return Container( child: Stack( children: [ WeatherBg( weatherType: weatherType, width: width, height: height, ), ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/common/loading_dialog.dart
import 'package:flutter/material.dart'; class LoadingDialog extends Dialog { final String text; LoadingDialog({Key key, @required this.text}) : super(key: key); @override Widget build(BuildContext context) { return new Material( type: MaterialType.transparency, child: new Center( child: new SizedBox( width: 120.0, height: 120.0, child: new Container( decoration: ShapeDecoration( color: Color(0xffffffff), shape: RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(8.0), ), ), ), child: new Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new CircularProgressIndicator(), new Padding( padding: const EdgeInsets.only( top: 20.0, ), child: new Text(text), ), ], ), ), ), ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/common/blur_rect.dart
import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/dimen_constant.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; class BlurRectWidget extends StatefulWidget { final Widget child; final double sigmaX; final double sigmaY; final BorderRadius borderRadius; final Color color; const BlurRectWidget({ Key key, this.child, this.sigmaX, this.sigmaY, this.borderRadius, this.color }) : super(key: key); @override _BlurRectWidgetState createState() => _BlurRectWidgetState(); } class _BlurRectWidgetState extends State<BlurRectWidget> { @override Widget build(BuildContext context) { return Container( child: Stack( children: [ ClipRRect( borderRadius: widget.borderRadius == null ? BorderRadius.circular(DimenConstant.cardRadius) : widget.borderRadius, child: BackdropFilter( filter: ImageFilter.blur( sigmaX: this.widget.sigmaX != null ? this.widget.sigmaX : 5, sigmaY: this.widget.sigmaY != null ? this.widget.sigmaY : 5, ), child: Container( color: this.widget.color == null ? Colors.black12 : this.widget.color, child: this.widget.child, ), ), ), ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/common/loading_view.dart
import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/views/common/blur_rect.dart'; enum ViewState { loading, error, empty } class StateView extends StatelessWidget { final ViewState weatherState; StateView( {Key key, this.weatherState = ViewState.loading}) : super(key: key); String _getDesc() { if (weatherState == ViewState.empty) { return "暂无数据"; } else if (weatherState == ViewState.error) { return "请求失败"; } else { return "正在加载中"; } } Widget _getWidget() { if (weatherState == ViewState.empty) { return Image.asset( "assets/images/empty.png", color: Color(0xffffffff), width: 60, height: 60, ); } else if (weatherState == ViewState.error) { return Image.asset( "assets/images/error.png", color: Color(0xffffffff), width: 60, height: 60, ); } else { return CircularProgressIndicator(); } } @override Widget build(BuildContext context) { return new Material( type: MaterialType.transparency, child: new Center( child: new SizedBox( width: 120.0, height: 120.0, child: BlurRectWidget( color: Colors.black.withAlpha(100), child: new Container( width: 120.0, height: 120.0, decoration: ShapeDecoration( shape: RoundedRectangleBorder( borderRadius: BorderRadius.all( Radius.circular(8.0), ), ), ), child: new Column( mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ _getWidget(), new Padding( padding: const EdgeInsets.only( top: 20.0, ), child: new Text( _getDesc(), style: TextStyle( color: Color(0xffffffff), ), ), )], ), ), ), ), ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/common/ota_dialog.dart
import 'dart:math'; import 'dart:ui'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/ota_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/views/common/wave_view.dart'; import 'package:flutter_weather_bg/bg/weather_bg.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; import 'package:ota_update/ota_update.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; var radius = 20.0; var width = 250.0; var height = 350.0; var weatherType = WeatherType.sunny; class OTADialog extends Dialog { final desc; final versionName; final apkUrl; OTADialog(this.desc, this.versionName, this.apkUrl, {Key key}) : super(key: key); @override Widget build(BuildContext context) { weatherType = WeatherType.values[Random().nextInt(WeatherType.values.length)]; return new Material( type: MaterialType.transparency, child: new Center( child: new SizedBox( width: width, height: height, child: ClipPath( clipper: ShapeBorderClipper( shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(radius))), child: Stack( children: [ WeatherBg( weatherType: weatherType, width: width, height: height, ), BackdropFilter( filter: ImageFilter.blur( sigmaX: 1, sigmaY: 1, ), child: Container( width: width, height: height, color: Colors.white.withAlpha(60), ), ), OTAContentWidget(desc, versionName, apkUrl), ], ), ), ), ), ); } } class OTAContentWidget extends StatefulWidget { final desc; final versionName; final apkUrl; OTAContentWidget(this.desc, this.versionName, this.apkUrl, {Key key}) : super(key: key); @override _OTAContentWidgetState createState() => _OTAContentWidgetState(); } class _OTAContentWidgetState extends State<OTAContentWidget> { double progress = 0.0; OtaStatus otaStatus; Widget _buildWaveBg() { weatherPrint("_buildWaveBg progress: $progress, status: $otaStatus"); if (otaStatus == OtaStatus.DOWNLOADING) { return WaveProgress( Size(width, height), WeatherUtil.getColor(weatherType)[0], progress); } return Container(); } Widget _buildUpdateButton() { String buttonText = "立即更新"; VoidCallback action = startOta; if (otaStatus == OtaStatus.DOWNLOADING) { buttonText = "正在下载..."; action = null; } else if (otaStatus == OtaStatus.PERMISSION_NOT_GRANTED_ERROR) { buttonText = "请打开权限"; action = null; } return Container( margin: EdgeInsets.only(left: 40, right: 40, bottom: 25, top: 10), width: width, child: MaterialButton( onPressed: action, disabledColor: WeatherUtil.getColor(weatherType)[1].withOpacity(0.5), shape: RoundedRectangleBorder( side: BorderSide.none, borderRadius: BorderRadius.circular(25), ), child: Text( buttonText, style: TextStyle( color: Colors.white, fontSize: 13, fontWeight: FontWeight.w500), ), color: WeatherUtil.getColor(weatherType)[1], ), ); } void startOta() async { UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "start"); OTAUtils.startOTA( widget.apkUrl, (event) { otaStatus = event.status; if (event.status == OtaStatus.DOWNLOADING) { progress = int.parse(event.value).toDouble(); } else if (event.status == OtaStatus.INSTALLING) { Navigator.of(context).pop(); } setState(() {}); }); } @override Widget build(BuildContext context) { return Container( width: width, height: height, child: Stack( children: [ _buildWaveBg(), Positioned( right: 10, top: 10, child: IconButton( icon: Icon( Icons.close, color: Colors.white.withAlpha(188), ), onPressed: () { UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "cancel"); Navigator.of(context).pop(); }, ), ), Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Container( margin: EdgeInsets.only(top: 20, left: 30), child: Row( crossAxisAlignment: CrossAxisAlignment.end, children: [ Text( "版本更新", style: TextStyle( color: Colors.white, fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, fontSize: 20, shadows: [ Shadow( color: Colors.black.withAlpha(100), offset: Offset(6, 3), blurRadius: 4) ], ), ), SizedBox( width: 20, ), Text( widget.versionName, style: TextStyle( color: Colors.white, fontStyle: FontStyle.italic, fontWeight: FontWeight.bold, fontSize: 15, shadows: [ Shadow( color: Colors.black.withAlpha(80), offset: Offset(2, 1), blurRadius: 4) ], ), ) ], ), ), Container( margin: EdgeInsets.only(left: 15, top: 30), child: Text( "更新内容", style: TextStyle( fontWeight: FontWeight.bold, fontSize: 15, color: Colors.white), ), ), Expanded( child: SingleChildScrollView( physics: BouncingScrollPhysics(), child: Container( margin: EdgeInsets.only(left: 15, top: 15, right: 12), child: Text( widget.desc, style: TextStyle(color: Colors.white, height: 1.8), ), ), ), ), _buildUpdateButton(), ], ), ], ), ); } }
0
mirrored_repositories/SimplicityWeather/lib/views
mirrored_repositories/SimplicityWeather/lib/views/common/wave_view.dart
import 'dart:math'; import 'package:flutter/material.dart'; class WaveProgress extends StatefulWidget { final Size size; final Color fillColor; final double progress; WaveProgress(this.size, this.fillColor, this.progress); @override WaveProgressState createState() => new WaveProgressState(); } class WaveProgressState extends State<WaveProgress> with TickerProviderStateMixin { AnimationController waveController; AnimationController progressController; @override void initState() { super.initState(); progressController = AnimationController( vsync: this, duration: Duration(milliseconds: 3000), ); waveController = AnimationController( vsync: this, duration: Duration(milliseconds: 800), ); progressController.animateTo(widget.progress); waveController.repeat(); } @override void dispose() { waveController.dispose(); progressController.dispose(); super.dispose(); } @override void didUpdateWidget(WaveProgress oldWidget) { super.didUpdateWidget(oldWidget); if (oldWidget.progress != widget.progress) { progressController.animateTo(widget.progress / 100.0); } } @override Widget build(BuildContext context) { return new Container( width: widget.size.width, height: widget.size.height, child: new AnimatedBuilder( animation: waveController, builder: (BuildContext context, Widget child) { return new CustomPaint( painter: WaveProgressPainter( waveController, progressController, widget.fillColor)); })); } } class WaveProgressPainter extends CustomPainter { Animation<double> _waveAnimation; Animation<double> _progressAnimation; Color fillColor; Paint topPaint = new Paint(); Paint bottomPaint = new Paint(); WaveProgressPainter( this._waveAnimation, this._progressAnimation, this.fillColor) : super(repaint: _waveAnimation); @override void paint(Canvas canvas, Size size) { bottomPaint.color = fillColor.withOpacity(0.45); double progress = _progressAnimation.value; double frequency = 3.2; double waveHeight = 4.0; double currentHeight = (1 - progress) * size.height; Path path = Path(); path.moveTo(0.0, currentHeight); for (double i = 0.0; i < size.width; i++) { path.lineTo( i, currentHeight + sin((i / size.width * 2 * pi * frequency) + (_waveAnimation.value * 2 * pi) + pi * 1) * waveHeight); } path.lineTo(size.width, size.height); path.lineTo(0.0, size.height); path.close(); canvas.drawPath(path, bottomPaint); topPaint.color = fillColor; frequency = 1.8; waveHeight = 10.0; path.reset(); path.moveTo(0.0, currentHeight); for (double i = 0.0; i < size.width; i++) { path.lineTo( i, currentHeight + sin((i / size.width * 2 * pi * frequency) + (_waveAnimation.value * 2 * pi)) * waveHeight); } path.lineTo(size.width, size.height); path.lineTo(0.0, size.height); path.close(); canvas.drawPath(path, topPaint); } @override bool shouldRepaint(CustomPainter oldDelegate) => true; }
0
mirrored_repositories/SimplicityWeather/lib
mirrored_repositories/SimplicityWeather/lib/app/router.dart
import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/example/anim_view.dart'; import 'package:flutter_dynamic_weather/example/grid_view.dart'; import 'package:flutter_dynamic_weather/example/list_view.dart'; import 'package:flutter_dynamic_weather/example/main.dart'; import 'package:flutter_dynamic_weather/example/page_view.dart'; import 'package:flutter_dynamic_weather/views/pages/about/about_page.dart'; import 'package:flutter_dynamic_weather/views/pages/manager/manager_page.dart'; import 'package:flutter_dynamic_weather/views/pages/search/search_page.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; import 'utils/router_utils.dart'; class AppAnalysis extends NavigatorObserver { @override void didPush(Route<dynamic> route, Route<dynamic> previousRoute) { if (route.settings.name != null) { weatherPrint("AppAnalysis didPush: ${route.settings.name}"); UmengAnalyticsPlugin.event(AnalyticsConstant.pageShow, label: "${route.settings.name}"); UmengAnalyticsPlugin.pageStart(route.settings.name); } } @override void didPop(Route<dynamic> route, Route<dynamic> previousRoute) { if (route.settings.name != null) { weatherPrint("AppAnalysis didPop: ${route.settings.name}"); UmengAnalyticsPlugin.pageEnd(route.settings.name); } } } class WeatherRouter { static const String CHANNEL_NAME = 'com.example.flutter_dynamic_weather/router'; static const String manager = 'manager'; static const String search = 'search'; static const String about = 'about'; static const String example = 'example'; static const String minute = 'minute'; static const String zhuge = 'zhuge'; static const String jike = 'jike'; static const String routePage = "page"; static const String routeList = "list"; static const String routeGrid = "grid"; static const String routeAnim = "anim"; static Future<Null> jumpToNativePage(String name) async { MethodChannel channel = MethodChannel(CHANNEL_NAME); channel.invokeMethod("startActivity", {"name": name}); } static Route<dynamic> generateRoute(RouteSettings settings) { switch (settings.name) { //根据名称跳转相应页面 case search: return FadeRouter( child: SearchPage(), settings: RouteSettings(name: search)); case manager: return FadeRouter( child: ManagerPage(), settings: RouteSettings(name: manager)); case about: return FadeRouter(child: AboutPage(), settings: settings); case example: return FadeRouter(child: MyExampleApp(), settings: settings); case routePage: return FadeRouter(child: PageViewWidget(), settings: settings); case routeList: return FadeRouter(child: ListViewWidget(), settings: settings); case routeGrid: return FadeRouter(child: GridViewWidget(), settings: settings); case routeAnim: return FadeRouter(child: AnimViewWidget(), settings: settings); default: return MaterialPageRoute( builder: (_) => Scaffold( body: Center( child: Text('No route defined for ${settings.name}'), ), )); } } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/widget_state.dart
enum WidgetState { loading, success, error, }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/analytics_constant.dart
class AnalyticsConstant { static const String initMainPage = "init_home_page"; static const String cityTotalCount = "city_total_count"; static const String locatedCityName = "located_city_name"; static const String searchCityName = "search_city_name"; static const String bottomSheet = "bottom_sheet"; static const String aboutClick = "about_click"; static const String pageShow = "page_show"; static const String weatherType = "weather_type"; static const String ota = "ota"; static const String aboutWeatherClick = "aboutWeatherClick"; static const String exampleClick = "example_click"; }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/common_extension.dart
extension StringExtension on String { DateTime get dateTime => DateTime.parse(this.substring(0, this.length - 6)); // 对时间进行裁剪 } extension NumExtension on int { String get gapTime => this < 10 ? "0$this" : "$this"; // 缺0 补0 }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/dimen_constant.dart
class DimenConstant { static const singleDayForecastHeight = 90.0; static const dayForecastMarginBottom = 20.0; static const aqiMinuteHeight = 50.0; static const aqiChartHeight = 120.0; static const realtimeMinHeight = 400.0; static const mainMarginStartEnd = 10.0; static const cardMarginStartEnd = 15.0; static const dayMiddleMargin = 15.0; static const cardRadius = 16.0; }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/weather_type.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_weather_bg/flutter_weather_bg.dart'; enum LifeIndexType { ultraviolet, carWashing, dressing, comfort, coldRisk, typhoon } class WeatherUtils { static final weatherMap = { "CLEAR_DAY": "晴", "CLEAR_NIGHT": "晴", "PARTLY_CLOUDY_DAY": "多云", "PARTLY_CLOUDY_NIGHT": "多云", "CLOUDY": "阴", "LIGHT_HAZE": "霾", "MODERATE_HAZE": "霾", "HEAVY_HAZE": "霾", "LIGHT_RAIN": "小雨", "MODERATE_RAIN": "中雨", "HEAVY_RAIN": "大雨", "STORM_RAIN": "暴雨", "FOG": "雾", "LIGHT_SNOW": "小雪", "MODERATE_SNOW": "中雪", "HEAVY_SNOW": "大雪", "STORM_SNOW": "暴雪", "DUST": "浮尘", "SAND": "沙尘", "WIND": "大风", }; static final weatherTypeMap = { "CLEAR_DAY": WeatherType.sunny, "CLEAR_NIGHT": WeatherType.sunnyNight, "PARTLY_CLOUDY_DAY": WeatherType.cloudy, "PARTLY_CLOUDY_NIGHT": WeatherType.cloudyNight, "CLOUDY": WeatherType.overcast, "LIGHT_HAZE": WeatherType.hazy, "MODERATE_HAZE": WeatherType.hazy, "HEAVY_HAZE": WeatherType.hazy, "LIGHT_RAIN": WeatherType.lightRainy, "MODERATE_RAIN": WeatherType.middleRainy, "HEAVY_RAIN": WeatherType.heavyRainy, "STORM_RAIN": WeatherType.thunder, "FOG": WeatherType.foggy, "LIGHT_SNOW": WeatherType.lightSnow, "MODERATE_SNOW": WeatherType.middleSnow, "HEAVY_SNOW": WeatherType.heavySnow, "STORM_SNOW": WeatherType.heavySnow, "DUST": WeatherType.dusty, "SAND": WeatherType.dusty, "WIND": WeatherType.overcast, }; static List<Color> getColor(WeatherType weatherType) { switch (weatherType) { case WeatherType.sunny: return [Color(0xFF0071D1), Color(0xFF6DA6E4)]; case WeatherType.sunnyNight: return [Color(0xFF061E74), Color(0xFF275E9A)]; case WeatherType.cloudy: return [Color(0xFF5C82C1), Color(0xFF95B1DB)]; case WeatherType.cloudyNight: return [Color(0xFF2C3A60), Color(0xFF4B6685)]; case WeatherType.overcast: return [Color(0xFF8FA3C0), Color(0xFF8C9FB1)]; case WeatherType.lightRainy: return [Color(0xFF556782), Color(0xFF7c8b99)]; case WeatherType.middleRainy: return [Color(0xFF3A4B65), Color(0xFF495764)]; case WeatherType.heavyRainy: case WeatherType.thunder: return [Color(0xFF3B434E), Color(0xFF565D66)]; case WeatherType.hazy: return [Color(0xFF989898), Color(0xFF4B4B4B)]; case WeatherType.foggy: return [Color(0xFFA6B3C2), Color(0xFF737F88)]; case WeatherType.lightSnow: return [Color(0xFF6989BA), Color(0xFF9DB0CE)]; case WeatherType.middleSnow: return [Color(0xFF8595AD), Color(0xFF95A4BF)]; case WeatherType.heavySnow: return [Color(0xFF98A2BC), Color(0xFFA7ADBF)]; case WeatherType.dusty: return [Color(0xFFB99D79), Color(0xFF6C5635)]; default: return [Color(0xFF0071D1), Color(0xFF6DA6E4)]; } } static convertDesc(String skycon) { if (weatherMap[skycon] == null || weatherMap[skycon].isEmpty) { return "晴"; } return weatherMap[skycon]; } static WeatherType convertWeatherType(String skycon) { if (weatherMap[skycon] == null || weatherMap[skycon].isEmpty) { return WeatherType.sunny; } return weatherTypeMap[skycon]; } static String getAqiDesc(int aqi) { if (aqi >= 0 && aqi <= 50) { return "优"; } if (aqi > 50 && aqi <= 100) { return "良"; } if (aqi > 100 && aqi <= 150) { return "轻度污染"; } if (aqi > 150 && aqi <= 200) { return "中度污染"; } if (aqi > 200 && aqi <= 300) { return "重度污染"; } if (aqi > 300) { return "严重污染"; } return ""; } static String getCityName(CityModel cityModel) { String cityName = ""; if (cityModel.isLocated == true) { cityName = "${cityModel.district} ${cityModel.street}"; } else { String city = ""; if (cityModel.city != null && cityModel.city.isNotEmpty) { city = "${cityModel.city}"; } String district = ""; if (cityModel.district != null && cityModel.district.isNotEmpty) { district = "${cityModel.district}"; } String province = ""; if (cityModel.province != null && cityModel.province.isNotEmpty) { province = "${cityModel.province}"; } if (city != "") { cityName = "$city $district"; } else { cityName = "$province"; } } return cityName; } static String getTemperatureDesc(WeatherModelResultDaily resultDaily) { if (resultDaily == null || resultDaily.temperature == null || resultDaily.temperature.isEmpty || resultDaily.temperature.length <= 1) { return ""; } var dayTemperature = resultDaily.temperature[1].max; var nightTemperature = resultDaily.temperature[1].min; return "$dayTemperature°/$nightTemperature°"; } static bool isRainy(WeatherType weatherType) { return weatherType == WeatherType.lightRainy || weatherType == WeatherType.middleRainy || weatherType == WeatherType.heavyRainy || weatherType == WeatherType.thunder; } static bool isSnow(WeatherType weatherType) { return weatherType == WeatherType.lightSnow || weatherType == WeatherType.middleSnow || weatherType == WeatherType.heavySnow; } static bool isSnowRain(WeatherType weatherType) { return isRainy(weatherType) || isSnow(weatherType); } static String getWeatherIcon(WeatherType weatherType) { switch (weatherType) { case WeatherType.sunny: return "assets/images/weather/sunny.png"; case WeatherType.sunnyNight: return "assets/images/weather/sunny_night.png"; case WeatherType.cloudy: return "assets/images/weather/cloudy.png"; case WeatherType.overcast: return "assets/images/weather/overcast.png"; case WeatherType.lightRainy: return "assets/images/weather/small_rain.png"; case WeatherType.middleRainy: return "assets/images/weather/middle_rain.png"; case WeatherType.heavyRainy: case WeatherType.thunder: return "assets/images/weather/heavy_rain.png"; case WeatherType.hazy: return "assets/images/weather/foggy.png"; case WeatherType.foggy: return "assets/images/weather/foggy.png"; case WeatherType.lightSnow: return "assets/images/weather/small_snow.png"; case WeatherType.middleSnow: return "assets/images/weather/middle_snow.png"; case WeatherType.heavySnow: return "assets/images/weather/heavy_snow.png"; case WeatherType.dusty: return "assets/images/weather/sandy.png"; case WeatherType.cloudyNight: return "assets/images/weather/cloudy_night.png"; default: return "assets/images/weather/sunny.png"; } } static String getLifeIndexDesc(LifeIndexType indexType) { switch (indexType) { case LifeIndexType.dressing: return "穿衣指数"; case LifeIndexType.coldRisk: return "感冒指数"; case LifeIndexType.comfort: return "舒适指数"; case LifeIndexType.carWashing: return "洗车指数"; case LifeIndexType.typhoon: return "台风路径"; default: return "紫外线"; } } static String getLifeIndexIcon(LifeIndexType lifeIndexType) { switch (lifeIndexType) { case LifeIndexType.dressing: return "assets/images/dressing.png"; case LifeIndexType.coldRisk: return "assets/images/coldRisk.png"; case LifeIndexType.comfort: return "assets/images/comfort.png"; case LifeIndexType.carWashing: return "assets/images/carWashing.png"; case LifeIndexType.typhoon: return "assets/images/typhoon.png"; default: return "assets/images/ultraviolet.png"; } } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/res/string_constant.dart
class StringConstant { static const appName = "动态天气"; }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/time_util.dart
/// create by 张风捷特烈 on 2020/6/17 /// contact me by email [email protected] /// 说明: import 'package:flutter_dynamic_weather/app/res/common_extension.dart'; final double _kMillisLimit = 1000.0; final double _kSecondsLimit = 60 * _kMillisLimit; final double _kMinutesLimit = 60 * _kSecondsLimit; final double _kHourLimit = 24 * _kMinutesLimit; final double _kDaysLimit = 30 * _kHourLimit; class TimeUtil { ///日期格式转换 static String time2string(DateTime date, {bool just = false}) { if (just) { return _getDateStr(date); } int subTimes = DateTime.now().millisecondsSinceEpoch - date.millisecondsSinceEpoch; if (subTimes < _kMillisLimit) { return "刚刚"; } else if (subTimes < _kSecondsLimit) { return (subTimes / _kMillisLimit).round().toString() + " 秒前"; } else if (subTimes < _kMinutesLimit) { return (subTimes / _kSecondsLimit).round().toString() + "分钟前"; } else if (subTimes < _kHourLimit) { return (subTimes / _kMinutesLimit).round().toString() + "小时前"; } else if (subTimes < _kDaysLimit) { return (subTimes / _kHourLimit).round().toString() + "天前"; } else { return _getDateStr(date); } } static String _getDateStr(DateTime date) { if (date == null || date.toString() == null) { return ""; } else if (date.toString().length < 10) { return date.toString(); } return date.toString().substring(0, 10); } static String getWeatherDayDesc(String time) { DateTime targetTime = time.dateTime; DateTime nowTime = DateTime.now(); if (targetTime.day == nowTime.day) { return "今天"; } else if (targetTime.day == nowTime.day + 1) { return "明天"; } else if (targetTime.day == nowTime.day - 1) { return "昨天"; } else { return "${_getWeekDes(targetTime.weekday)}"; } } static String _getWeekDes(int weekDay) { switch (weekDay) { case 1: return "周一"; case 2: return "周二"; case 3: return "周三"; case 4: return "周四"; case 5: return "周五"; case 6: return "周六"; case 7: return "周日"; } return ""; } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/toast.dart
import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:toast/toast.dart'; class ToastUtils { static snap(BuildContext context, String msg, {duration = const Duration( milliseconds: 600), SnackBarAction action, Color color}) { Scaffold.of(context).showSnackBar(SnackBar( content: Text(msg), duration: duration, action: action, backgroundColor: color ?? Theme .of(context) .primaryColor, )); } static show(String msg, BuildContext context, {int duration = 1, int gravity = 2, Color backgroundColor = const Color(0xAA000000), Color textColor = Colors.white, double backgroundRadius = 20, Border border}) { Toast.show(msg, context, duration: duration, backgroundColor: backgroundColor, textColor: textColor, backgroundRadius: backgroundRadius, border: border); } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/print_utils.dart
import 'package:flutter/widgets.dart'; typedef WeatherPrint = void Function(String message, {int wrapWidth, String tag}); const DEBUG = true; WeatherPrint weatherPrint = debugPrintThrottled; void debugPrintThrottled(String message, {int wrapWidth, String tag}) { if (DEBUG) { debugPrint("flutter-weather: $tag: $message", wrapWidth: wrapWidth); } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/color_utils.dart
import 'dart:math'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; //Color randomColor(){/// 用来返回一个随机色 //var random=Random(); //var a = random.nextInt(256);//透明度值 //var r = random.nextInt(256);//红值 //var g = random.nextInt(256);//绿值 //var b = random.nextInt(256);//蓝值 //return Color.fromARGB(a, r, g, b);//生成argb模式的颜色 //} //Color randomColor(int limitA){ // var random=Random(); // var a = limitA+random.nextInt(256-limitA);//透明度值 // var r = random.nextInt(256);//红值 // var g = random.nextInt(256);//绿值 // var b = random.nextInt(256);//蓝值 // return Color.fromARGB(a, r, g, b);//生成argb模式的颜色 //} class ColorUtils { /// 使用方法: /// var color1=ColorUtils.parse("#33428A43"); /// var color2=ColorUtils.parse("33428A43"); /// var color3=ColorUtils.parse("#428A43"); ///var color4=ColorUtils.parse("428A43"); /// static Color parse(String code) { Color result =Colors.red; var value = 0 ; if (code.contains("#")) { try { value = int.parse(code.substring(1), radix: 16); } catch (e) { weatherPrint(e.toString()); } switch (code.length) { case 1 + 6://6位 result = Color(value + 0xFF000000); break; case 1 + 8://8位 result = Color(value); break; default: result =Colors.red; } }else { try { value = int.parse(code, radix: 16); } catch (e) { weatherPrint(e.toString()); } switch (code.length) { case 6: result = Color(value + 0xFF000000); break; case 8: result = Color(value); break; default: result =Colors.red; } } return result; } static String colorString(Color color) => "#${color.value.toRadixString(16).padLeft(8, '0').toUpperCase()}"; }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/ui_utils.dart
import 'dart:ui' as ui; import 'package:flutter/material.dart'; class UiUtils { static ui.Paragraph getParagraph(String text, double textSize, {Color color = Colors.white, double itemWidth = 100}) { var pb = ui.ParagraphBuilder(ui.ParagraphStyle( textAlign: TextAlign.center, //居中 fontSize: textSize, //大小 )); pb.addText(text); pb.pushStyle(ui.TextStyle(color: color)); var paragraph = pb.build()..layout(ui.ParagraphConstraints(width: itemWidth)); return paragraph; } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/ota_utils.dart
import 'dart:io'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/toast.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:ota_update/ota_update.dart'; import 'package:package_info/package_info.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; class OTAUtils { static startOTA(String url, void onData(OtaEvent event)) async { try { OtaUpdate() .execute( url, destinationFilename: 'SimplicityWeather.apk', ) .listen( (OtaEvent event) { onData(event); print('status: ${event.status}, value: ${event.value}'); if (event.status == OtaStatus.DOWNLOAD_ERROR) { ToastUtils.show("下载失败", globalKey.currentContext); UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "download_error"); } else if (event.status == OtaStatus.INTERNAL_ERROR) { ToastUtils.show("未知失败", globalKey.currentContext); UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "internal_error"); } else if (event.status == OtaStatus.PERMISSION_NOT_GRANTED_ERROR) { UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "permission_not_granted_error"); ToastUtils.show("请打开权限", globalKey.currentContext); } else if (event.status == OtaStatus.INSTALLING) { UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "installing"); ToastUtils.show("正在安装...", globalKey.currentContext); } }, ); } catch (e) { print('Failed to make OTA update. Details: $e'); } } static initOTA() async { if (!Platform.isAndroid) { return; } var otaData = await WeatherApi().getOTA(); if (otaData != null && otaData["data"] != null) { String url = otaData["data"]["url"]; String desc = otaData["data"]["desc"]; String versionName = ""; // todo 添加 versionName 的接口配置 int appCode = int.parse(otaData["data"]["appCode"]); var packageInfo = await PackageInfo.fromPlatform(); var number = int.parse(packageInfo.buildNumber); if (appCode > number) { UmengAnalyticsPlugin.event(AnalyticsConstant.ota, label: "needOTA"); showOTADialog(url, desc, versionName); } } } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/shared_preference_util.dart
import 'dart:convert'; import 'package:flutter/material.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:shared_preferences/shared_preferences.dart'; class SPUtil { static SharedPreferences _sp; static const KEY_CITY_MODELS = "city_models"; static const KEY_WEATHER_MODELS = "weather_models"; static Future<SharedPreferences> get sp async { _sp = _sp ?? await SharedPreferences.getInstance(); return _sp; } static Future<bool> saveCityModels(List<CityModel> cityModels) async { weatherPrint("saveCityModels ${cityModels?.length}", tag: "SPUtil"); var prefs = await sp; var encodeStr = json.encode(cityModels); weatherPrint('sp -encode: $encodeStr'); return prefs.setString(KEY_CITY_MODELS, encodeStr); } static Future<List<CityModel>> getCityModels() async { weatherPrint("getCityModels", tag: "SPUtil"); var prefs = await sp; var parseValue = prefs.getString(KEY_CITY_MODELS); weatherPrint('sp-get: $parseValue'); if (parseValue == null || parseValue == "") { return null; } List<dynamic> decodeObject = json.decode(parseValue); List<CityModel> model = []; decodeObject.forEach((element) { model.add(CityModel.fromJson(element)); }); return model; } static Future<bool> saveAllWeatherModels(Map<String, String> allWeatherDat) async { weatherPrint("saveAllWeatherModels ${allWeatherDat?.length}", tag: "SPUtil"); var prefs = await sp; var encodeStr = json.encode(allWeatherDat); return prefs.setString(KEY_WEATHER_MODELS, encodeStr); } static Future<Map<String, String>> getAllWeatherModels() async { weatherPrint("getAllWeatherModels", tag: "SPUtil"); var prefs = await sp; var parseValue = prefs.getString(KEY_WEATHER_MODELS); if (parseValue == null || parseValue == "") { return null; } Map<String, String> model = new Map<String, String>.from(json.decode(parseValue)); return model; } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/image_utils.dart
import 'dart:ui'; import 'dart:ui' as ui; import 'dart:typed_data'; import 'package:flutter/services.dart'; class ImageUtils { static Future<ui.Image> getImage(String asset) async { ByteData data = await rootBundle.load(asset); Codec codec = await ui.instantiateImageCodec(data.buffer.asUint8List()); FrameInfo fi = await codec.getNextFrame(); return fi.image; } }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/router_utils.dart
import 'package:flutter/material.dart'; //缩放路由动画 class ScaleRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; ScaleRouter({this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => ScaleTransition( scale: Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: a1, curve: curve)), child: child, ), ); } //渐变透明路由动画 class FadeRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; final RouteSettings settings; FadeRouter({this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn, this.settings}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, settings : settings, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => FadeTransition( opacity: Tween(begin: 0.1, end: 1.0).animate( CurvedAnimation(parent: a1, curve:curve,)), child: child, )); } //旋转路由动画 class RotateRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; RotateRouter({this.child, this.durationMs = 500,this.curve=Curves.fastOutSlowIn}) : super( pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: durationMs), transitionsBuilder: (context, a1, a2, child) => RotationTransition( turns: Tween(begin: 0.1, end: 1.0).animate( CurvedAnimation(parent: a1, curve:curve,)), child: child, )); } //右--->左 class Right2LeftRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Right2LeftRouter({this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2)=>child, transitionsBuilder:(ctx,a1,a2, child,) => SlideTransition( child: child, position: Tween<Offset>( begin: Offset(1.0, 0.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), )); } //左--->右 class Left2RightRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; List<int> mapper; Left2RightRouter({this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :assert(true),super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2){return child;}, transitionsBuilder:(ctx,a1,a2,child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(-1.0, 0.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //上--->下 class Top2BottomRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Top2BottomRouter({this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2){return child;}, transitionsBuilder:(ctx,a1,a2, child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(0.0,-1.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //下--->上 class Bottom2TopRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; Bottom2TopRouter({this.child,this.durationMs=500,this.curve=Curves.fastOutSlowIn}) :super( transitionDuration:Duration(milliseconds: durationMs), pageBuilder:(ctx,a1,a2)=> child, transitionsBuilder:(ctx,a1,a2, child,) { return SlideTransition( position: Tween<Offset>( begin: Offset(0.0, 1.0), end: Offset(0.0, 0.0),).animate( CurvedAnimation(parent: a1, curve: curve)), child: child ); }); } //缩放+透明+旋转路由动画 class ScaleFadeRotateRouter<T> extends PageRouteBuilder<T> { final Widget child; final int durationMs; final Curve curve; ScaleFadeRotateRouter({this.child, this.durationMs = 1000,this.curve=Curves.fastOutSlowIn}) : super( transitionDuration: Duration(milliseconds: durationMs), pageBuilder: (ctx, a1, a2)=>child,//页面 transitionsBuilder: (ctx, a1, a2, Widget child,) => RotationTransition(//旋转动画 turns: Tween(begin: 0.0, end: 1.0).animate(CurvedAnimation( parent: a1, curve: curve, )), child: ScaleTransition(//缩放动画 scale: Tween(begin: 0.0, end: 1.0).animate( CurvedAnimation(parent: a1, curve: curve)), child: FadeTransition(opacity://透明度动画 Tween(begin: 0.5, end: 1.0).animate(CurvedAnimation(parent: a1, curve: curve)), child: child,), ), )); } //无动画 class NoAnimRouter<T> extends PageRouteBuilder<T> { final Widget child; NoAnimRouter({this.child}) : super( opaque: false, pageBuilder: (context, animation, secondaryAnimation) => child, transitionDuration: Duration(milliseconds: 0), transitionsBuilder: (context, animation, secondaryAnimation, child) => child); }
0
mirrored_repositories/SimplicityWeather/lib/app
mirrored_repositories/SimplicityWeather/lib/app/utils/location_util.dart
class LocationUtil { static String convertToFlag(String longitude, String latitude) { return "$longitude,$latitude"; } static List<String> parseFlag(String flag) { return flag.split(",").toList(); } static String getCityFlag(String key) { return key.substring(0, key.lastIndexOf(",")); } static String convertCityFlag(String cityFlag, bool isLocated) { return "$cityFlag,$isLocated"; } }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/weather/weather_event.dart
part of 'weather_bloc.dart'; abstract class WeatherEvent extends Equatable { const WeatherEvent(); } class FetchWeatherDataEvent extends WeatherEvent { final CityModel cityModel; const FetchWeatherDataEvent(this.cityModel); @override List<Object> get props => [cityModel]; }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/weather/weather_state.dart
part of 'weather_bloc.dart'; abstract class WeatherState extends Equatable { const WeatherState(); } class WeatherLoading extends WeatherState { final CityModel cityModel; const WeatherLoading(this.cityModel); @override List<Object> get props => [cityModel]; } class WeatherFailed extends WeatherState{ final CityModel cityModel; const WeatherFailed(this.cityModel); @override List<Object> get props => [cityModel]; } class WeatherSuccess extends WeatherState{ final WeatherModelEntity entity; final CityModel cityModel; const WeatherSuccess(this.entity, this.cityModel); @override List<Object> get props => [entity, cityModel]; }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/weather/weather_bloc.dart
import 'dart:async'; import 'dart:convert'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; part 'weather_event.dart'; part 'weather_state.dart'; class WeatherBloc extends Bloc<WeatherEvent, WeatherState> { final WeatherApi weatherApi; WeatherBloc(this.weatherApi) : super(WeatherLoading(null)); @override Stream<WeatherState> mapEventToState( WeatherEvent event, ) async* { weatherPrint('WeatherBloc || mapEventToState event: ${event.runtimeType}'); if (event is FetchWeatherDataEvent) { yield* _mapFetchWeatherToState(event.cityModel); } } Stream<WeatherState> _mapFetchWeatherToState(CityModel cityModel) async* { weatherPrint("开始请求 ${cityModel.city} 城市的数据....flag: ${cityModel.cityFlag}"); yield WeatherLoading(cityModel); final resData = await weatherApi.loadWeatherData( LocationUtil.parseFlag(cityModel.cityFlag)[0], LocationUtil.parseFlag(cityModel.cityFlag)[1]); var allWeatherData = await SPUtil.getAllWeatherModels(); if (allWeatherData == null || allWeatherData.isEmpty) { allWeatherData = {}; } if (resData == null) { weatherPrint("城市获取失败"); yield WeatherFailed(cityModel); } else { var resDataStr = json.encode(resData); if (cityModel.isLocated == true && allWeatherData.isNotEmpty) { String needRemoveKey = ""; allWeatherData.forEach((key, value) { if (key.contains("true")) { needRemoveKey = key; return; } }); if (needRemoveKey != "") { weatherPrint('需要先移除定位城市 key: $needRemoveKey'); allWeatherData.remove(needRemoveKey); } } // 如果是定位城市,需要先移除定位城市,然后在添加 allWeatherData[LocationUtil.convertCityFlag(cityModel.cityFlag, cityModel.isLocated)] = resDataStr; await SPUtil.saveAllWeatherModels(allWeatherData); final weatherData = WeatherModelEntity().fromJson(resData); if (weatherData == null) { weatherPrint("城市获取失败"); yield WeatherFailed(cityModel); } else { weatherPrint("城市获取成功"); eventBus.fire(MainBgChangeEvent()); yield WeatherSuccess(weatherData, cityModel); } } } }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/city/city_event.dart
part of 'city_bloc.dart'; abstract class CityEvent extends Equatable { const CityEvent(); } class FetchCityDataEvent extends CityEvent { @override List<Object> get props => []; } class RequestLocationEvent extends CityEvent { const RequestLocationEvent(); @override List<Object> get props => []; } class InsertCityData extends CityEvent { final CityModel cityModel; const InsertCityData(this.cityModel); @override List<Object> get props => [cityModel]; } class DeleteCityData extends CityEvent { final String cityFlag; const DeleteCityData(this.cityFlag); @override List<Object> get props => [cityFlag]; }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/city/city_state.dart
part of 'city_bloc.dart'; abstract class CityState extends Equatable { const CityState(); } @immutable class CitySuccess extends CityState { final List<CityModel> cityModels; CitySuccess(this.cityModels); @override List<Object> get props => [cityModels]; } @immutable class CityInit extends CityState { CityInit(); @override List<Object> get props => []; } @immutable class LocationSuccessState extends CityState { LocationSuccessState(); @override List<Object> get props => []; }
0
mirrored_repositories/SimplicityWeather/lib/bloc
mirrored_repositories/SimplicityWeather/lib/bloc/city/city_bloc.dart
import 'dart:async'; import 'dart:collection'; import 'package:amap_location_fluttify/amap_location_fluttify.dart'; import 'package:bloc/bloc.dart'; import 'package:equatable/equatable.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/rendering.dart'; import 'package:flutter_dynamic_weather/app/res/analytics_constant.dart'; import 'package:flutter_dynamic_weather/app/res/weather_type.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; import 'package:flutter_dynamic_weather/app/utils/print_utils.dart'; import 'package:flutter_dynamic_weather/app/utils/shared_preference_util.dart'; import 'package:flutter_dynamic_weather/app/utils/toast.dart'; import 'package:flutter_dynamic_weather/event/change_index_envent.dart'; import 'package:flutter_dynamic_weather/model/city_model_entity.dart'; import 'package:flutter_dynamic_weather/model/weather_model_entity.dart'; import 'package:flutter_dynamic_weather/net/weather_api.dart'; import 'package:flutter_dynamic_weather/views/app/flutter_app.dart'; import 'package:umeng_analytics_plugin/umeng_analytics_plugin.dart'; part 'city_event.dart'; part 'city_state.dart'; class CityBloc extends Bloc<CityEvent, CityState> { final WeatherApi weatherApi; CityBloc(this.weatherApi) : super(CityInit()); @override Stream<CityState> mapEventToState( CityEvent event, ) async* { weatherPrint('cityBloc || mapEventToState evet: ${event.runtimeType}'); if (event is FetchCityDataEvent) { yield* mapFetchCityDataEventToState(); } else if (event is RequestLocationEvent) { showAppDialog(loadingMsg: "正在定位"); weatherPrint("开始请求定位..."); Location location = await AmapLocation.instance.fetchLocation(); weatherPrint("定位结束: $location"); CityModel cityModel = convert(location); cityModel.displayedName = WeatherUtils.getCityName(cityModel); UmengAnalyticsPlugin.event(AnalyticsConstant.locatedCityName, label: "${cityModel.displayedName}"); List<CityModel> cityModels = []; if (cityModel.latitude == 0.0 || cityModel.longitude == 0.0) { ToastUtils.show("高德 API 调用上限, 默认添加北京,请见谅", globalKey.currentContext, duration: 5); cityModel = _buildDefault(); } cityModels = await insertCityMode(cityModel); weatherPrint('定位成功 location: $cityModel'); eventBus.fire(MainBgChangeEvent()); Navigator.of(globalKey.currentContext).pop(); yield CitySuccess(cityModels); } else if (event is InsertCityData) { weatherPrint("开始添加城市 ${event.cityModel.cityFlag}"); List<CityModel> cacheModels = await SPUtil.getCityModels(); bool needInsert = true; if (cacheModels != null && cacheModels.isNotEmpty) { cacheModels.forEach((element) { if (event.cityModel.cityFlag == element.cityFlag) { needInsert = false; return; } }); } if (!needInsert) { weatherPrint("城市已存在,不需要插入"); return; } List<CityModel> cityModels = []; if (event.cityModel.latitude != 0.0 && event.cityModel.longitude != 0.0) { cityModels = await insertCityMode(event.cityModel); } eventBus.fire(MainBgChangeEvent()); yield CitySuccess(cityModels); } else if (event is DeleteCityData) { weatherPrint("开始删除城市 ${event.cityFlag}"); List<CityModel> cacheModels = await SPUtil.getCityModels(); CityModel needRemoveModel; cacheModels.forEach((element) { if (element.cityFlag == event.cityFlag) { needRemoveModel = element; } }); if (needRemoveModel != null) { weatherPrint("从 cityModels 删除成功!!"); cacheModels.remove(needRemoveModel); await SPUtil.saveCityModels(cacheModels); Map<String, String> allData = await SPUtil.getAllWeatherModels(); String key = LocationUtil.convertCityFlag( needRemoveModel.cityFlag, needRemoveModel.isLocated); if (allData != null && allData.containsKey(key)) { allData.remove(key); await SPUtil.saveAllWeatherModels(allData); weatherPrint("从 AllWeatherModels 删除成功!!"); } eventBus.fire(MainBgChangeEvent()); yield CitySuccess(cacheModels); } } } CityModel _buildDefault() { CityModel cityModel = CityModel( latitude: 39.904989, longitude: 116.405285, country: "中国", province: "北京市", district: "东城区", displayedName: "北京市", isLocated: true, ); return cityModel; } Future<List<CityModel>> insertCityMode(CityModel cityModel) async { weatherPrint("开始插入城市数据 $cityModel"); List<CityModel> cityModels = await SPUtil.getCityModels(); if (cityModels == null) { cityModels = []; } if (cityModels.isNotEmpty) { CityModel needRemoveModel; cityModels.forEach((element) { if (cityModel.isLocated == true) { needRemoveModel = element; return; } }); if (needRemoveModel != null) { weatherPrint("定位城市需要先从 CityModels 中移除"); cityModels.remove(needRemoveModel); } } if (cityModel.isLocated == true) { cityModels.insert(0, cityModel); } else { cityModels.add(cityModel); } await SPUtil.saveCityModels(cityModels); weatherPrint("插入成功后 size: ${cityModels?.length}"); return cityModels; } CityModel convert(Location location) { return CityModel( latitude: location.latLng.latitude, longitude: location.latLng.longitude, country: location.country, province: location.province, city: location.city, district: location.district, poiName: location.poiName, street: location.street, streetNumber: location.streetNumber, isLocated: true); } Stream<CityState> mapFetchCityDataEventToState() async* { weatherPrint("开始获取本地城市列表数据===="); var cityModels = await SPUtil.getCityModels(); if (cityModels == null || cityModels.isEmpty) { // 本地没有城市数据 weatherPrint('本地列表数据为空'); yield CityInit(); } else { weatherPrint('成功获取到城市列表数据 size: ${cityModels.length}'); UmengAnalyticsPlugin.event(AnalyticsConstant.cityTotalCount, label: "${cityModels.length}"); yield CitySuccess(cityModels); } } }
0
mirrored_repositories/SimplicityWeather/lib
mirrored_repositories/SimplicityWeather/lib/model/weather_model_entity.dart
import 'package:flutter_dynamic_weather/generated/json/base/json_convert_content.dart'; import 'package:flutter_dynamic_weather/generated/json/base/json_field.dart'; class WeatherModelEntity with JsonConvert<WeatherModelEntity> { String status; @JSONField(name: "api_version") String apiVersion; @JSONField(name: "api_status") String apiStatus; String lang; String unit; int tzshift; String timezone; @JSONField(name: "server_time") int serverTime; List<double> location; WeatherModelResult result; } class WeatherModelResult with JsonConvert<WeatherModelResult> { WeatherModelResultRealtime realtime; WeatherModelResultMinutely minutely; WeatherModelResultHourly hourly; WeatherModelResultDaily daily; int primary; @JSONField(name: "forecast_keypoint") String forecastKeypoint; } class WeatherModelResultRealtime with JsonConvert<WeatherModelResultRealtime> { String status; int temperature; double humidity; double cloudrate; String skycon; double visibility; double dswrf; WeatherModelResultRealtimeWind wind; double pressure; @JSONField(name: "apparent_temperature") double apparentTemperature; WeatherModelResultRealtimePrecipitation precipitation; @JSONField(name: "air_quality") WeatherModelResultRealtimeAirQuality airQuality; @JSONField(name: "life_index") WeatherModelResultRealtimeLifeIndex lifeIndex; } class WeatherModelResultRealtimeWind with JsonConvert<WeatherModelResultRealtimeWind> { double speed; double direction; } class WeatherModelResultRealtimePrecipitation with JsonConvert<WeatherModelResultRealtimePrecipitation> { WeatherModelResultRealtimePrecipitationLocal local; WeatherModelResultRealtimePrecipitationNearest nearest; } class WeatherModelResultRealtimePrecipitationLocal with JsonConvert<WeatherModelResultRealtimePrecipitationLocal> { String status; String datasource; int intensity; } class WeatherModelResultRealtimePrecipitationNearest with JsonConvert<WeatherModelResultRealtimePrecipitationNearest> { String status; int distance; int intensity; } class WeatherModelResultRealtimeAirQuality with JsonConvert<WeatherModelResultRealtimeAirQuality> { int pm25; int pm10; int o3; int so2; int no2; int co; WeatherModelResultRealtimeAirQualityAqi aqi; WeatherModelResultRealtimeAirQualityDescription description; } class WeatherModelResultRealtimeAirQualityAqi with JsonConvert<WeatherModelResultRealtimeAirQualityAqi> { int chn; int usa; } class WeatherModelResultRealtimeAirQualityDescription with JsonConvert<WeatherModelResultRealtimeAirQualityDescription> { String usa; String chn; } class WeatherModelResultRealtimeLifeIndex with JsonConvert<WeatherModelResultRealtimeLifeIndex> { WeatherModelResultRealtimeLifeIndexUltraviolet ultraviolet; WeatherModelResultRealtimeLifeIndexComfort comfort; } class WeatherModelResultRealtimeLifeIndexUltraviolet with JsonConvert<WeatherModelResultRealtimeLifeIndexUltraviolet> { int index; String desc; } class WeatherModelResultRealtimeLifeIndexComfort with JsonConvert<WeatherModelResultRealtimeLifeIndexComfort> { int index; String desc; } class WeatherModelResultMinutely with JsonConvert<WeatherModelResultMinutely> { String status; String datasource; @JSONField(name: "precipitation_2h") List<int> precipitation2h; List<int> precipitation; List<int> probability; String description; } class WeatherModelResultHourly with JsonConvert<WeatherModelResultHourly> { String status; String description; List<WeatherModelResultHourlyPrecipitation> precipitation; List<WeatherModelResultHourlyTemperature> temperature; List<WeatherModelResultHourlyWind> wind; List<WeatherModelResultHourlyHumidity> humidity; List<WeatherModelResultHourlyCloudrate> cloudrate; List<WeatherModelResultHourlySkycon> skycon; List<WeatherModelResultHourlyPressure> pressure; List<WeatherModelResultHourlyVisibility> visibility; List<WeatherModelResultHourlyDswrf> dswrf; @JSONField(name: "air_quality") WeatherModelResultHourlyAirQuality airQuality; } class WeatherModelResultHourlyPrecipitation with JsonConvert<WeatherModelResultHourlyPrecipitation> { String datetime; int value; } class WeatherModelResultHourlyTemperature with JsonConvert<WeatherModelResultHourlyTemperature> { String datetime; int value; } class WeatherModelResultHourlyWind with JsonConvert<WeatherModelResultHourlyWind> { String datetime; double speed; double direction; } class WeatherModelResultHourlyHumidity with JsonConvert<WeatherModelResultHourlyHumidity> { String datetime; double value; } class WeatherModelResultHourlyCloudrate with JsonConvert<WeatherModelResultHourlyCloudrate> { String datetime; double value; } class WeatherModelResultHourlySkycon with JsonConvert<WeatherModelResultHourlySkycon> { String datetime; String value; } class WeatherModelResultHourlyPressure with JsonConvert<WeatherModelResultHourlyPressure> { String datetime; double value; } class WeatherModelResultHourlyVisibility with JsonConvert<WeatherModelResultHourlyVisibility> { String datetime; double value; } class WeatherModelResultHourlyDswrf with JsonConvert<WeatherModelResultHourlyDswrf> { String datetime; double value; } class WeatherModelResultHourlyAirQuality with JsonConvert<WeatherModelResultHourlyAirQuality> { List<WeatherModelResultHourlyAirQualityAqi> aqi; List<WeatherModelResultHourlyAirQualityPm25> pm25; } class WeatherModelResultHourlyAirQualityAqi with JsonConvert<WeatherModelResultHourlyAirQualityAqi> { String datetime; WeatherModelResultHourlyAirQualityAqiValue value; } class WeatherModelResultHourlyAirQualityAqiValue with JsonConvert<WeatherModelResultHourlyAirQualityAqiValue> { int chn; int usa; } class WeatherModelResultHourlyAirQualityPm25 with JsonConvert<WeatherModelResultHourlyAirQualityPm25> { String datetime; int value; } class WeatherModelResultDaily with JsonConvert<WeatherModelResultDaily> { String status; List<WeatherModelResultDailyAstro> astro; List<WeatherModelResultDailyPrecipitation> precipitation; List<WeatherModelResultDailyTemperature> temperature; List<WeatherModelResultDailyWind> wind; List<WeatherModelResultDailyHumidity> humidity; List<WeatherModelResultDailyCloudrate> cloudrate; List<WeatherModelResultDailyPressure> pressure; List<WeatherModelResultDailyVisibility> visibility; List<WeatherModelResultDailyDswrf> dswrf; @JSONField(name: "air_quality") WeatherModelResultDailyAirQuality airQuality; List<WeatherModelResultDailySkycon> skycon; @JSONField(name: "skycon_08h_20h") List<WeatherModelResultDailySkycon08h20h> skycon08h20h; @JSONField(name: "skycon_20h_32h") List<WeatherModelResultDailySkycon20h32h> skycon20h32h; @JSONField(name: "life_index") WeatherModelResultDailyLifeIndex lifeIndex; } class WeatherModelResultDailyAstro with JsonConvert<WeatherModelResultDailyAstro> { String date; WeatherModelResultDailyAstroSunrise sunrise; WeatherModelResultDailyAstroSunset sunset; } class WeatherModelResultDailyAstroSunrise with JsonConvert<WeatherModelResultDailyAstroSunrise> { String time; } class WeatherModelResultDailyAstroSunset with JsonConvert<WeatherModelResultDailyAstroSunset> { String time; } class WeatherModelResultDailyPrecipitation with JsonConvert<WeatherModelResultDailyPrecipitation> { String date; int max; int min; int avg; } class WeatherModelResultDailyTemperature with JsonConvert<WeatherModelResultDailyTemperature> { String date; int max; int min; double avg; } class WeatherModelResultDailyWind with JsonConvert<WeatherModelResultDailyWind> { String date; WeatherModelResultDailyWindMax max; WeatherModelResultDailyWindMin min; WeatherModelResultDailyWindAvg avg; } class WeatherModelResultDailyWindMax with JsonConvert<WeatherModelResultDailyWindMax> { double speed; double direction; } class WeatherModelResultDailyWindMin with JsonConvert<WeatherModelResultDailyWindMin> { double speed; double direction; } class WeatherModelResultDailyWindAvg with JsonConvert<WeatherModelResultDailyWindAvg> { double speed; double direction; } class WeatherModelResultDailyHumidity with JsonConvert<WeatherModelResultDailyHumidity> { String date; double max; double min; double avg; } class WeatherModelResultDailyCloudrate with JsonConvert<WeatherModelResultDailyCloudrate> { String date; double max; double min; double avg; } class WeatherModelResultDailyPressure with JsonConvert<WeatherModelResultDailyPressure> { String date; double max; double min; double avg; } class WeatherModelResultDailyVisibility with JsonConvert<WeatherModelResultDailyVisibility> { String date; double max; double min; int avg; } class WeatherModelResultDailyDswrf with JsonConvert<WeatherModelResultDailyDswrf> { String date; double max; int min; double avg; } class WeatherModelResultDailyAirQuality with JsonConvert<WeatherModelResultDailyAirQuality> { List<WeatherModelResultDailyAirQualityAqi> aqi; List<WeatherModelResultDailyAirQualityPm25> pm25; } class WeatherModelResultDailyAirQualityAqi with JsonConvert<WeatherModelResultDailyAirQualityAqi> { String date; WeatherModelResultDailyAirQualityAqiMax max; WeatherModelResultDailyAirQualityAqiAvg avg; WeatherModelResultDailyAirQualityAqiMin min; } class WeatherModelResultDailyAirQualityAqiMax with JsonConvert<WeatherModelResultDailyAirQualityAqiMax> { int chn; int usa; } class WeatherModelResultDailyAirQualityAqiAvg with JsonConvert<WeatherModelResultDailyAirQualityAqiAvg> { double chn; double usa; } class WeatherModelResultDailyAirQualityAqiMin with JsonConvert<WeatherModelResultDailyAirQualityAqiMin> { int chn; int usa; } class WeatherModelResultDailyAirQualityPm25 with JsonConvert<WeatherModelResultDailyAirQualityPm25> { String date; int max; double avg; int min; } class WeatherModelResultDailySkycon with JsonConvert<WeatherModelResultDailySkycon> { String date; String value; } class WeatherModelResultDailySkycon08h20h with JsonConvert<WeatherModelResultDailySkycon08h20h> { String date; String value; } class WeatherModelResultDailySkycon20h32h with JsonConvert<WeatherModelResultDailySkycon20h32h> { String date; String value; } class WeatherModelResultDailyLifeIndex with JsonConvert<WeatherModelResultDailyLifeIndex> { List<WeatherModelResultDailyLifeIndexUltraviolet> ultraviolet; List<WeatherModelResultDailyLifeIndexCarWashing> carWashing; List<WeatherModelResultDailyLifeIndexDressing> dressing; List<WeatherModelResultDailyLifeIndexComfort> comfort; List<WeatherModelResultDailyLifeIndexColdRisk> coldRisk; } class WeatherModelResultDailyLifeIndexUltraviolet with JsonConvert<WeatherModelResultDailyLifeIndexUltraviolet> { String date; String index; String desc; } class WeatherModelResultDailyLifeIndexCarWashing with JsonConvert<WeatherModelResultDailyLifeIndexCarWashing> { String date; String index; String desc; } class WeatherModelResultDailyLifeIndexDressing with JsonConvert<WeatherModelResultDailyLifeIndexDressing> { String date; String index; String desc; } class WeatherModelResultDailyLifeIndexComfort with JsonConvert<WeatherModelResultDailyLifeIndexComfort> { String date; String index; String desc; } class WeatherModelResultDailyLifeIndexColdRisk with JsonConvert<WeatherModelResultDailyLifeIndexColdRisk> { String date; String index; String desc; }
0
mirrored_repositories/SimplicityWeather/lib
mirrored_repositories/SimplicityWeather/lib/model/city_data.dart
class CityData { static const cityLevel = "city"; static const districtLevel = "district"; String name; String center; String level; bool isLocated; @override String toString() { return 'CityData{name: $name, center: $center, level: $level, longitude: $longitude, latitude: $latitude}'; } CityData(this.name, this.center, {this.level, this.isLocated}); get longitude { return center.split(",")[0]; } get latitude { return center.split(",")[1]; } }
0
mirrored_repositories/SimplicityWeather/lib
mirrored_repositories/SimplicityWeather/lib/model/city_model_entity.dart
import 'package:equatable/equatable.dart'; import 'package:flutter_dynamic_weather/app/utils/location_util.dart'; class CityModel extends Equatable { double latitude; double longitude; String country; // 中国 String province; // 江苏省 String city; // 南京市 String district; // 建邺区 String poiName; // 南京原力数字艺术培训中心 String street; // 西城路 String streetNumber; // 8号 bool isLocated = false; String displayedName; String get cityFlag { return LocationUtil.convertToFlag("$longitude", "$latitude"); } CityModel( {this.latitude, this.longitude, this.country, this.province, this.city, this.district, this.poiName, this.street, this.streetNumber, this.isLocated, this.displayedName}); @override String toString() { return 'CityModel{latitude: $latitude, longitude: $longitude, displayedName: $displayedName, country: $country, province: $province, city: $city, district: $district, poiName: $poiName, street: $street, streetNumber: $streetNumber, isLocated: $isLocated}'; } Map toJson() { return { "latitude": latitude, "longitude": longitude, "country": country, "province": province, "city": city, "district": district, "poiName": poiName, "street": street, "streetNumber": streetNumber, "isLocated": isLocated, "displayedName": displayedName }; } CityModel.fromJson(Map<String, dynamic> json) { latitude = json['latitude']; longitude = json['longitude']; country = json['country']; province = json['province']; district = json['district']; poiName = json['poiName']; street = json['street']; streetNumber = json['streetNumber']; isLocated = json['isLocated']; city = json['city']; displayedName = json['displayedName']; } @override List<Object> get props => [latitude, longitude]; }
0
mirrored_repositories/SimplicityWeather/lib
mirrored_repositories/SimplicityWeather/lib/model/district_model_entity.dart
import 'package:flutter_dynamic_weather/generated/json/base/json_convert_content.dart'; class DistrictModelEntity with JsonConvert<DistrictModelEntity> { String status; String info; String count; List<DistrictModelDistrict> districts; } class DistrictModelDistrict with JsonConvert<DistrictModelDistrict> { String adcode; String name; String center; String level; List<DistrictModelDistrictsDistrict> districts; } class DistrictModelDistrictsDistrict with JsonConvert<DistrictModelDistrictsDistrict> { String adcode; String name; String center; String level; List<dynamic> districts; }
0